7e7381b209
withCORS 中间件:仅白名单 origin(默认 pangolin.yanmeiai.com + pages.dev)返回 CORS 头、 OPTIONS 直接 204;New(svc, corsOrigins) + main 读 PAY_CORS_ORIGINS。为官网下单页跨域调 pay 铺路。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
41 lines
1.2 KiB
Go
41 lines
1.2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// withCORS lets the browser storefront (pangolin website) call the order API
|
|
// cross-origin. Auth is server-to-server / bearer-less here (no cookies), so
|
|
// Allow-Credentials is not needed. Only whitelisted origins get CORS headers;
|
|
// OPTIONS preflight is answered directly.
|
|
func withCORS(next http.Handler, allowed map[string]bool) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
origin := r.Header.Get("Origin")
|
|
if origin != "" && allowed[origin] {
|
|
h := w.Header()
|
|
h.Set("Access-Control-Allow-Origin", origin)
|
|
h.Add("Vary", "Origin")
|
|
h.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
h.Set("Access-Control-Allow-Headers", "Content-Type")
|
|
h.Set("Access-Control-Max-Age", "600")
|
|
}
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// parseOrigins builds the allowed-origin set from a comma-separated list.
|
|
func parseOrigins(csv string) map[string]bool {
|
|
m := map[string]bool{}
|
|
for _, o := range strings.Split(csv, ",") {
|
|
if o = strings.TrimSpace(o); o != "" {
|
|
m[o] = true
|
|
}
|
|
}
|
|
return m
|
|
}
|