2020-03-04 13:40:53 +02:00
|
|
|
package cors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2021-09-17 11:17:12 +02:00
|
|
|
type Config struct {
|
|
|
|
AllowOrigin string
|
|
|
|
AllowCredentials bool
|
|
|
|
AllowMethods string
|
|
|
|
AllowHeaders string
|
2020-03-04 13:40:53 +02:00
|
|
|
}
|
|
|
|
|
2021-09-17 11:17:12 +02:00
|
|
|
// CombinedCORSHandler wraps a server and provides CORS headers
|
|
|
|
func CombinedCORSHandler(h http.Handler, config *Config) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if config != nil {
|
|
|
|
SetHeaders(w, r, config)
|
|
|
|
}
|
|
|
|
if r.Method == "OPTIONS" {
|
|
|
|
return
|
|
|
|
}
|
2020-03-04 13:40:53 +02:00
|
|
|
|
2021-09-17 11:17:12 +02:00
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
})
|
2020-03-04 13:40:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetHeaders sets the CORS headers
|
2021-09-17 11:17:12 +02:00
|
|
|
func SetHeaders(w http.ResponseWriter, _ *http.Request, config *Config) {
|
2020-03-04 13:40:53 +02:00
|
|
|
set := func(w http.ResponseWriter, k, v string) {
|
|
|
|
if v := w.Header().Get(k); len(v) > 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set(k, v)
|
|
|
|
}
|
2021-09-17 11:17:12 +02:00
|
|
|
//For forward-compatible code, default values may not be provided in the future
|
|
|
|
if config.AllowCredentials {
|
|
|
|
set(w, "Access-Control-Allow-Credentials", "true")
|
2020-03-04 13:40:53 +02:00
|
|
|
} else {
|
2021-09-17 11:17:12 +02:00
|
|
|
set(w, "Access-Control-Allow-Credentials", "false")
|
|
|
|
}
|
|
|
|
if config.AllowOrigin == "" {
|
2020-03-04 13:40:53 +02:00
|
|
|
set(w, "Access-Control-Allow-Origin", "*")
|
2021-09-17 11:17:12 +02:00
|
|
|
} else {
|
|
|
|
set(w, "Access-Control-Allow-Origin", config.AllowOrigin)
|
|
|
|
}
|
|
|
|
if config.AllowMethods == "" {
|
|
|
|
set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE")
|
|
|
|
} else {
|
|
|
|
set(w, "Access-Control-Allow-Methods", config.AllowMethods)
|
|
|
|
}
|
|
|
|
if config.AllowHeaders == "" {
|
|
|
|
set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
|
|
|
} else {
|
|
|
|
set(w, "Access-Control-Allow-Headers", config.AllowHeaders)
|
2020-03-04 13:40:53 +02:00
|
|
|
}
|
|
|
|
}
|