Files
httpmw/cors.go

52 lines
1.2 KiB
Go
Raw Permalink Normal View History

package httpmw
import (
"net/http"
"strings"
)
const (
allowedMethods = "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS"
allowedHeaders = "Content-Type, Authorization, X-Request-ID"
)
// CORS applies Cross-Origin Resource Sharing headers.
// origins is the allowed origins list. Pass []string{"*"} for development.
func CORS(origins []string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
allowed := false
for _, o := range origins {
if o == "*" || o == origin {
allowed = true
break
}
}
if allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", allowedMethods)
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}
// originAllowed is a helper for tests.
func originAllowed(origins []string, origin string) bool {
for _, o := range origins {
if o == "*" {
return true
}
if strings.EqualFold(o, origin) {
return true
}
}
return false
}