corsMiddleware adds CORS headers
(next http.Handler)
| 34 | |
| 35 | // corsMiddleware adds CORS headers |
| 36 | func corsMiddleware(next http.Handler) http.Handler { |
| 37 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 38 | // Allow all origins for development |
| 39 | // In production, restrict to specific origins |
| 40 | origin := r.Header.Get("Origin") |
| 41 | if origin == "" { |
| 42 | origin = "*" |
| 43 | } |
| 44 | |
| 45 | w.Header().Set("Access-Control-Allow-Origin", origin) |
| 46 | w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") |
| 47 | w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With") |
| 48 | w.Header().Set("Access-Control-Allow-Credentials", "true") |
| 49 | w.Header().Set("Access-Control-Max-Age", "86400") |
| 50 | |
| 51 | // Handle preflight |
| 52 | if r.Method == http.MethodOptions { |
| 53 | w.WriteHeader(http.StatusNoContent) |
| 54 | return |
| 55 | } |
| 56 | |
| 57 | next.ServeHTTP(w, r) |
| 58 | }) |
| 59 | } |