如何在Golang中处理HTTP Header_Golang Web请求头操作方法

Go 的 http.Header 是 map[string][]string 的封装,需用 Set/Add/Get 方法操作以确保大小写归一化;Header 必须在 WriteHeader 或 Write 前设置,CORS 配置需严格匹配来源与凭据策略。

Go 的 http.Header 是 map 的封装,不是普通 map

直接对 http.Headerheader["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 已是小写归一化后的形式

客户端请求中读取 Header 的典型陷阱

http.HandlerFunc 里,r.Header 看起来能直接读,但某些字段(如 Content-LengthHost)可能不在其中——它们被 HTTP/1.1 解析器提取到 Request 结构体字段里了。比如 r.Hostr.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 是否已解析
  • 自定义 header 如 X-Forwarded-For:用 r.Header.Get("X-Forwarded-For"),但要注意它可能是逗号分隔的多个 IP,需自行拆解

服务端写入响应 Header 的时机很关键

Header 必须在调用 WriteWriteHeader 之前设置。一旦 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 必须在这之前设好
  • 中间件里修改 header?确保它在链中足够靠前,且没提前触发 write
  • 想动态设置 header(比如根据 body 内容)?只能缓冲 body,或改用流式响应 + 自定义 writer 包装

跨域(CORS)相关 Header 的常见写法

手动写 Access-Control-Allow-

Origin 很容易出错,比如硬编码为 * 后又带 credentials,或漏掉 Access-Control-Allow-Headers 导致预检失败。

  • 允许任意来源(无 credentials):w.Header().Set("Access-Control-Allow-Origin", "*")
  • 允许特定来源(带 credentials):w.Header().Set("Access-Control-Allow-Origin", "https://example.com"),同时必须加:w.Header().Set("Access-Control-Allow-Credentials", "true")
  • 暴露自定义 header 给前端 JS:w.Header().Set("Access-Control-Expose-Headers", "X-Request-ID, X-RateLimit-Remaining")
  • 预检请求需要支持的 method 和 header: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 前后顺序、以及预检请求是否真被拦截处理。