45 lines
1.5 KiB
Go
45 lines
1.5 KiB
Go
package cors
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
// NewMiddleware builds a CORS middleware. When an exact origin from the
|
||
|
|
// allowed list matches the request's Origin header, that origin is echoed
|
||
|
|
// back and credentials are permitted. Requests without an allowed origin
|
||
|
|
// still pass through (the browser enforces the missing CORS headers), while
|
||
|
|
// preflight requests are answered directly with 204 and never reach the rest
|
||
|
|
// of the chain.
|
||
|
|
func NewMiddleware(origins, methods, headers []string) func(http.Handler) http.Handler {
|
||
|
|
allowed := make(map[string]struct{}, len(origins))
|
||
|
|
for _, origin := range origins {
|
||
|
|
allowed[strings.ToLower(strings.TrimSpace(origin))] = struct{}{}
|
||
|
|
}
|
||
|
|
|
||
|
|
methodsValue := strings.Join(methods, ", ")
|
||
|
|
headersValue := strings.Join(headers, ", ")
|
||
|
|
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
origin := r.Header.Get("Origin")
|
||
|
|
if origin != "" {
|
||
|
|
if _, ok := allowed[strings.ToLower(origin)]; ok {
|
||
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||
|
|
w.Header().Set("Access-Control-Allow-Methods", methodsValue)
|
||
|
|
w.Header().Set("Access-Control-Allow-Headers", headersValue)
|
||
|
|
w.Header().Set("Access-Control-Max-Age", "600")
|
||
|
|
w.Header().Add("Vary", "Origin")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if r.Method == http.MethodOptions {
|
||
|
|
w.WriteHeader(http.StatusNoContent)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|