Go 的 http.Header 是 map[string][]string 的封装,需用 Set/Add/Get 方法操作以确保大小写归一化;Header 必须在 WriteHeader 或 Write 前设置,CORS 配置需严格匹配来源与凭据策略。
http.Header 是 map 的封装,不是普通 map直接对 http.Header 做 header["X-User-ID"] = []string{"123"} 看似可行,但这是不安全的——它绕过了内部大小写归一化逻辑。Go 的 http.Header 实际是 map[string][]string,但所有 key 都被转为规范形式(如 "content-type"),而手动赋值不会触发这个转换,后续用 header.Get("Content-Type") 就可能拿不到值。
header.Set("X-Request-ID", "abc") 写入单值(会覆盖已有)header.Add("Set-Cookie", "a=1; Path=/")
header.Get("Authorization")(自动忽略大小写)for key, values := range header,但注意 key 已是小写归一化后的形式在 http.HandlerFunc 里,r.Header 看起来能直接读,但某些字段(如 Content-Length、Host)可能不在其中——它们被 HTTP/1.1 解析器提取到 Request 结构体字段里了。比如 r.Host 比 r.Header.Get("Host") 更可靠;r.ContentLength 是 int64,而 r.Header.Get("Content-Length") 是字符串,还可能为空。
r.Header.Get("User-Agent") ✅ 安全可用r.Header.Get("Referer") ✅(注意拼写是 Referer,不是 Referrer)r.Header.Get("Content-Type") ⚠️ 可能为空,优先用 r.Header.Get("Content-Type") 或检查 r.PostForm 是否已解析X-Forwarded-For:用 r.Header.Get("X-Forwarded-For"),但要注意它可能是逗号分隔的多个 IP,需自行拆解Header 必须在调用 Write 或 WriteHeader 之前设置。一旦 http.ResponseWriter 开始写 body(比如调用了 w.Write([]byte("ok"))),再调用 w.Header().Set(...) 就完全无效,也不会报错——header 被静默丢弃。
w.Header().Set("Cache-Control", "no-cache") → w.WriteHeader(200) → w.Write(...)
json.NewEncoder(w).Encode(...),它会自动调用 WriteHeader(200),所以 header 必须在这之前设好手动写 Access-Control-Allow-Origin 很容易出错,比如硬编码为 * 后又带 credentials,或漏掉 Access-Control-Allow-Headers 导致预检失败。
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Origin", "https://example.com"),同时必须加:w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-ID, X-RateLimit-Remaining")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"),w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With")
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control
-Allow-Origin", "https://myapp.com")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
Header 操作看着简单,但大小写归一、写入时机、CORS 组合逻辑这些点,线上出问题时往往难定位。别依赖“看起来能跑”,重点盯住 Set/Get 一致性、WriteHeader 前后顺序、以及预检请求是否真被拦截处理。