From 05922710b23abf5317195c385e26b12e91744cdc Mon Sep 17 00:00:00 2001 From: wangjia <809946525@qq.com> Date: Sat, 11 Jul 2026 15:33:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(server):=20CORS=20=E4=B8=AD=E9=97=B4?= =?UTF-8?q?=E4=BB=B6(=E7=99=BD=E5=90=8D=E5=8D=95=E8=B7=A8=E5=9F=9F,?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=94=A8=E6=88=B7=E4=B8=AD=E5=BF=83/?= =?UTF-8?q?=E5=AE=98=E7=BD=91=E5=89=8D=E7=AB=AF)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 控制面无 CORS 导致 pangolin.yanmeiai.com 的用户中心跨域打 api.yanmeiai.com 被浏览器拦(Network error)。 加白名单 CORS(env CORS_ALLOWED_ORIGINS,默认 https://pangolin.yanmeiai.com):回显 Origin、应答预检 OPTIONS、 放行 Authorization/Content-Type;不用 '*'、不放行 credentials(走 Bearer token)。 --- server/cmd/server/main.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go index 9b683d0..3bf0a72 100644 --- a/server/cmd/server/main.go +++ b/server/cmd/server/main.go @@ -123,6 +123,7 @@ func main() { r := chi.NewRouter() r.Use(chimw.Logger) r.Use(chimw.Recoverer) + r.Use(corsMiddleware(corsAllowedOrigins())) r.Use(apierr.Middleware) r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { @@ -590,3 +591,40 @@ func (a authDeviceRegistrar) CheckDeviceLimit(ctx context.Context, userID int64) } return &auth.DeviceLimit{MaxDevices: st.MaxDevices, Devices: briefs}, nil } + +// corsAllowedOrigins 从 env CORS_ALLOWED_ORIGINS(逗号分隔)读跨域白名单;默认放行官网/ +// 用户中心域。控制面走 Bearer token(无 cookie 会话),故不放行 credentials,只白名单回显 Origin。 +func corsAllowedOrigins() map[string]bool { + raw := os.Getenv("CORS_ALLOWED_ORIGINS") + if raw == "" { + raw = "https://pangolin.yanmeiai.com" + } + out := map[string]bool{} + for _, o := range strings.Split(raw, ",") { + if o = strings.TrimSpace(o); o != "" { + out[o] = true + } + } + return out +} + +// corsMiddleware 按白名单回显 Access-Control-Allow-Origin 并应答预检 OPTIONS。只放行白名单内 +// Origin(不用 "*"),允许 Authorization/Content-Type 头。非白名单来源不加任何 CORS 头(浏览器自然拦)。 +func corsMiddleware(allowed map[string]bool) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if origin := r.Header.Get("Origin"); origin != "" && allowed[origin] { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Add("Vary", "Origin") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") + w.Header().Set("Access-Control-Max-Age", "600") + } + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + next.ServeHTTP(w, r) + }) + } +}