cors.go37 lines, 1.2 KB
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "slices" |
| 6 | |
| 7 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 8 | ) |
| 9 | |
| 10 | // cors lets browser apps from origins call the API, and answers preflights. |
| 11 | func cors(origins []string) httpx.Middleware { |
| 12 | return func(next http.Handler) http.Handler { |
| 13 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 14 | h := w.Header() |
| 15 | h.Add("Vary", "Origin") |
| 16 | origin := r.Header.Get("Origin") |
| 17 | allowed := origin != "" && slices.Contains(origins, origin) |
| 18 | if allowed { |
| 19 | h.Set("Access-Control-Allow-Origin", origin) |
| 20 | h.Set("Access-Control-Expose-Headers", "X-Request-ID, Retry-After, "+ |
| 21 | "X-RateLimit-Limit, X-RateLimit-Remaining, Idempotent-Replayed") |
| 22 | } |
| 23 | if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { |
| 24 | if allowed { |
| 25 | h.Set("Access-Control-Allow-Methods", "GET, POST") |
| 26 | h.Set("Access-Control-Allow-Headers", |
| 27 | "Authorization, Content-Type, Idempotency-Key, X-Request-ID") |
| 28 | h.Set("Access-Control-Max-Age", "600") // the browser can skip preflights for ten minutes |
| 29 | } |
| 30 | // A preflight never reaches the routes, or Require. |
| 31 | w.WriteHeader(http.StatusNoContent) |
| 32 | return |
| 33 | } |
| 34 | next.ServeHTTP(w, r) |
| 35 | }) |
| 36 | } |
| 37 | } |