
本文详解 go 后端(使用 gorilla/mux 和 rs/cors)中 cors 配置失败的常见原因,重点解决预检(options)请求被拒绝问题,并提供标准库级中间件实现与最佳实践。
本文详解 go 后端(使用 gorilla/mux 和 rs/cors)中 cors 配置失败的常见原因,重点解决预检(options)请求被拒绝问题,并提供标准库级中间件实现与最佳实践。
在 Go Web 开发中,前端(如 Angular)与后端同域部署却仍触发跨域限制,往往源于对 CORS 预检机制(Preflight)的理解偏差或配置疏漏。从你提供的代码和请求/响应头可见:OPTIONS /users 请求返回 200 OK,但响应中缺失关键 CORS 头(如 Access-Control-Allow-Headers),且服务端未显式允许 OPTIONS 方法——这正是预检失败的根本原因。
? 核心问题定位
浏览器在发送带自定义请求头(如 access_token)或非简单方法(如 PATCH)的请求前,会先发起 OPTIONS 预检请求。而你的 cors.Options 配置中:
AllowedMethods: []string{"GET", "POST", "PATCH"}, // ❌ 缺少 "OPTIONS"
AllowedHeaders: []string{"a_custom_header", "content_type"}, // ❌ 未包含 "access_token"、"Accept" 等实际使用的头
导致预检响应缺少 Access-Control-Allow-Methods: OPTIONS 和 Access-Control-Allow-Headers: access_token,浏览器因此拒绝后续真实请求。
✅ 正确配置 rs/cors(推荐方案)
只需两处修正,即可启用完整 CORS 支持:
handler := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // 生产环境建议明确指定 origin,如 []string{"https://your-app.com"}
AllowedMethods: []string{"GET", "POST", "PATCH", "DELETE", "OPTIONS"}, // ✅ 显式添加 OPTIONS
AllowedHeaders: []string{
"access_token", // ✅ 匹配请求中的 Access-Control-Request-Headers
"content-type", // 注意:header 名不区分大小写,但建议统一小写
"accept",
"accept-language",
"origin",
"x-requested-with",
},
// 可选:启用凭证支持(如 cookies)
// AllowCredentials: true,
}).Handler(router)
⚠️ 注意事项:
AllowedHeaders中的"content_type"应改为"content-type"(标准 HTTP header 名);- 若前端发送
Authorization或其他自定义头,必须将其加入AllowedHeaders;AllowedOrigins: ["*"]与AllowCredentials: true不可共存,否则浏览器将报错;Vary响应头(如Vary: Origin)由rs/cors自动设置,无需手动干预。
?️ 手动实现轻量级 CORS 中间件(无第三方依赖)
若需更精细控制或避免引入额外依赖,可使用如下标准库兼容的装饰器:
type CORSHandler struct {
next http.Handler
}
func (h *CORSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers",
"access_token, content-type, accept, accept-language, origin, x-requested-with")
w.Header().Set("Access-Control-Expose-Headers", "Content-Length, X-Total-Count")
// 允许携带凭证(如 cookie)
// w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
h.next.ServeHTTP(w, r)
}
// 使用方式
r := mux.NewRouter()
r.HandleFunc("/authentication", handleAuthentication).Methods("GET", "POST")
r.HandleFunc("/callA", handleCallA).Methods("GET")
// ... 其他路由
http.ListenAndServe(":8000", &CORSHandler{next: r})
该中间件主动处理 OPTIONS 请求并返回 200 OK,同时为所有响应注入必要 CORS 头,完全兼容预检流程。
✅ 验证与调试建议
-
检查预检响应头:使用
curl -I -X OPTIONS http://localhost:8000/users -H "Origin: http://localhost:4200" -H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: access_token",确认响应含:Access-Control-Allow-Origin: http://localhost:4200 Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-Headers: access_token, content-type, ...
Angular 端注意:确保
HttpClient请求中withCredentials: true(如需 cookie)与后端AllowCredentials设置一致;日志辅助:在 handler 前添加日志,确认
OPTIONS请求是否到达服务器(例如log.Printf("Method: %s, Path: %s", r.Method, r.URL.Path))。
通过以上配置,你的 Go 后端将能稳定响应 Angular 发起的各类跨域请求,彻底解决预检失败问题。记住:CORS 的本质是浏览器安全策略,服务端只需按规范返回正确的响应头,无需“绕过”或“禁用”任何机制。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









