CORSMiddleware adds CORS headers based on allowed origins. If origins contains "*", all origins are allowed.
(next http.Handler, origins []string)
| 5 | // CORSMiddleware adds CORS headers based on allowed origins. |
| 6 | // If origins contains "*", all origins are allowed. |
| 7 | func CORSMiddleware(next http.Handler, origins []string) http.Handler { |
| 8 | allowAll := false |
| 9 | allowed := make(map[string]bool, len(origins)) |
| 10 | for _, o := range origins { |
| 11 | if o == "*" { |
| 12 | allowAll = true |
| 13 | } |
| 14 | allowed[o] = true |
| 15 | } |
| 16 | |
| 17 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 18 | origin := r.Header.Get("Origin") |
| 19 | |
| 20 | if origin != "" && (allowAll || allowed[origin]) { |
| 21 | allow := origin |
| 22 | if allowAll { |
| 23 | allow = "*" |
| 24 | } |
| 25 | w.Header().Set("Access-Control-Allow-Origin", allow) |
| 26 | w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") |
| 27 | w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-Auth-Token, X-Sentry-Auth, Authorization") |
| 28 | if !allowAll { |
| 29 | w.Header().Set("Access-Control-Allow-Credentials", "true") |
| 30 | } |
| 31 | w.Header().Set("Access-Control-Max-Age", "86400") |
| 32 | |
| 33 | if r.Method == http.MethodOptions { |
| 34 | w.WriteHeader(http.StatusNoContent) |
| 35 | return |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | next.ServeHTTP(w, r) |
| 40 | }) |
| 41 | } |
nothing calls this directly
no test coverage detected