BT  ·  2026-05-21

cors.go

 1package middleware
 2
 3import (
 4	"net/http"
 5	"strings"
 6)
 7
 8var allowedOrigins = []string{
 9	"https://rtw.run",
10	"https://next.rtw.run",
11}
12
13func isAllowedOrigin(origin string) bool {
14	if origin == "" {
15		return false
16	}
17	for _, allowed := range allowedOrigins {
18		if origin == allowed {
19			return true
20		}
21	}
22	// Allow localhost for development
23	if strings.HasPrefix(origin, "http://localhost:") {
24		return true
25	}
26	return false
27}
28
29func CORS(next http.Handler) http.Handler {
30	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31		origin := r.Header.Get("Origin")
32
33		if isAllowedOrigin(origin) {
34			w.Header().Set("Access-Control-Allow-Origin", origin)
35		}
36		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
37		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept-Language, Accept-Encoding, Accept, X-Requested-With")
38		w.Header().Set("Access-Control-Allow-Credentials", "true")
39		w.Header().Set("Access-Control-Max-Age", "86400")
40		w.Header().Add("Vary", "Origin")
41
42		if r.Method == http.MethodOptions {
43			w.WriteHeader(http.StatusNoContent)
44			return
45		}
46
47		next.ServeHTTP(w, r)
48	})
49}