net/http 默认不处理 CORS 是因设计上只做基础 HTTP 处理,所有 CORS 响应头(如 Access-Control-Allow-Origin)需手动设置或通过中间件(如 github.com/rs/cors)添加,否则浏览器拦截跨域请求。
net/http 默认不处理 CORSGo
标准库的 net/http 本身不内置 CORS 中间件,它只做基础 HTTP 处理,所有响应头(包括 Access-Control-Allow-Origin)都得手动设置。如果你没显式写,浏览器就收不到跨域许可,直接拦截请求——这不是 bug,是设计使然。
常见错误现象:Failed to fetch 或控制台报 No 'Access-Control-Allow-Origin' header is present,但后端日志里请求其实已成功执行。
gin 却没注册 Cors() 中间件)OPTIONS)必须返回 204 或 200,且不能跳过中间件逻辑github.com/rs/cors 快速启用(推荐)这是最稳定、维护活跃的第三方 CORS 库,支持细粒度配置,且对预检请求做了完整处理。它本质是一个 http.Handler 包装器,不影响原有路由逻辑。
安装:
go get github.com/rs/cors
基本用法示例:
package main
import (
"log"
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"ok": true}`))
})
// 包装 handler,允许来自 http://localhost:3000 的跨域请求
handler := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
ExposedHeaders: []string{"X-Total-Count"},
AllowCredentials: true,
}).Handler(mux)
log.Fatal(http.ListenAndServe(":8080", handler))
}
AllowedOrigins 不要设为 * 同时又开启 AllowCredentials: true,这会直接被浏览器拒绝ExposedHeaders 是前端 JS 能通过 response.headers.get() 读取的额外头字段,不配就拿不到OPTIONS),无需单独注册路由如果不想引入依赖,可以自己写一个中间件函数。注意:必须在所有路由前统一应用,且要显式处理 OPTIONS 请求。
关键点在于:预检请求不能落到业务 handler 上,否则可能因缺少 body 解析、JWT 验证等逻辑而失败。
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Expose-Headers", "X-Total-Count")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
// 使用方式:
// http.ListenAndServe(":8080", corsMiddleware(mux))
w.Header().Set() 会覆盖,建议集中设置浏览器是否放行跨域,只认这三个响应头,缺一不可:
Access-Control-Allow-Origin:必须精确匹配请求头中的 Origin,或为 *(但此时不能带凭证)Access-Control-Allow-Credentials:前端设了 credentials: 'include',后端就必须返回 true,且 Allow-Origin 不能是 *
Access-Control-Allow-Methods:列出前端实际使用的 HTTP 方法,大小写敏感,多余或遗漏都会导致预检失败用 curl -I 或浏览器 Network 面板检查响应头,比看 Go 日志更直接。尤其注意预检请求(OPTIONS)的响应头是否完整——很多问题出在这里,而不是主请求。