CORSMiddleware returns an http.Handler that applies CORS headers based on allowedOrigins. If allowedOrigins is empty, the middleware is a passthrough (CORS disabled). If "*" is in the list, any origin is allowed. Otherwise, only origins in the list are echoed back. OPTIONS preflight requests are sho
(allowedOrigins []string, next http.Handler)
| 23 | // Otherwise, only origins in the list are echoed back. |
| 24 | // OPTIONS preflight requests are short-circuited with 204 No Content before reaching the next handler. |
| 25 | func CORSMiddleware(allowedOrigins []string, next http.Handler) http.Handler { |
| 26 | if len(allowedOrigins) == 0 { |
| 27 | return next |
| 28 | } |
| 29 | |
| 30 | wildcard := false |
| 31 | allowed := make(map[string]struct{}, len(allowedOrigins)) |
| 32 | for _, o := range allowedOrigins { |
| 33 | if o == "*" { |
| 34 | wildcard = true |
| 35 | } |
| 36 | allowed[o] = struct{}{} |
| 37 | } |
| 38 | |
| 39 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 40 | origin := r.Header.Get("Origin") |
| 41 | if origin == "" { |
| 42 | next.ServeHTTP(w, r) |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | var matchedOrigin string |
| 47 | switch { |
| 48 | case wildcard: |
| 49 | matchedOrigin = "*" |
| 50 | default: |
| 51 | if _, ok := allowed[origin]; ok { |
| 52 | matchedOrigin = origin |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Always set Vary: Origin when the response depends on the Origin header, |
| 57 | // so HTTP caches don't serve a cached response for the wrong origin. |
| 58 | // Use Add to avoid clobbering any existing Vary values. |
| 59 | w.Header().Add("Vary", "Origin") |
| 60 | |
| 61 | if matchedOrigin == "" { |
| 62 | next.ServeHTTP(w, r) |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | w.Header().Set("Access-Control-Allow-Origin", matchedOrigin) |
| 67 | |
| 68 | if r.Method == http.MethodOptions { |
| 69 | w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS") |
| 70 | w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") |
| 71 | w.Header().Set("Access-Control-Max-Age", "86400") |
| 72 | w.WriteHeader(http.StatusNoContent) |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | next.ServeHTTP(w, r) |
| 77 | }) |
| 78 | } |