如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法

2次阅读

go 中设置 http 请求头需通过 *http.Request.Header 操作,必须在 client.Do() 前完成;Host、Content-Length 等由 Go 自动管理,手动设置无效或引发错误;推荐用 http.NewRequest 初始化并 Set/Add 头,jsON 请求须设 Content-Type 和 Accept。

如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法

在 Go 中设置 HTTP 请求头非常直接,核心是通过 *http.RequestHeader 字段(类型为 http.Header,本质是 map[String][]string)进行操作。关键点在于:请求头必须在调用 http.Client.Do() 之前设置,且部分头(如 HostContent-Length)由 Go 自动管理,手动设置可能被忽略或引发错误。

使用 http.NewRequest 设置初始 Header

创建请求时即可预设常用头,这是最推荐的起点方式:

req, err := http.NewRequest("GET", "https://api.example.com/data", nil) if err != nil {     log.Fatal(err) } // 设置单个值(会覆盖同名已有值) req.Header.Set("User-Agent", "Myapp/1.0") req.Header.Set("Accept", "application/json")  // 添加多个同名头(例如多个 cookie) req.Header.Add("Cookie", "sessionid=abc123") req.Header.Add("Cookie", "theme=dark")  // 设置 Authorization(推荐用 net/http/httpguts.IsTokenByte 验证 token 格式,但通常直接设即可) req.Header.Set("Authorization", "Bearer eyJhbGciOi...")

复用 Client 并动态修改 Header

若需对同一客户端发起多个不同头的请求,可在每次请求前修改 req.Header

client := &http.Client{}  req1, _ := http.NewRequest("POST", "https://api.example.com/login", body1) req1.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp1, _ := client.Do(req1)  req2, _ := http.NewRequest("GET", "https://api.example.com/profile", nil) req2.Header.Set("Authorization", "Bearer "+token) // 每次换新 token req2.Header.Set("Accept", "application/json; version=2") resp2, _ := client.Do(req2)

注意自动处理与禁止覆盖的 Header

Go 的 http.Transport 会对某些头做自动处理。手动设置可能无效,甚至导致 panic 或静默失败:

如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法

PicLumen

专业的ai图像生成和图像处理工具

如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法 348

查看详情 如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法

立即学习go语言免费学习笔记(深入)”;

  • Host:由 URL 解析自动填充,手动 Set("Host", ...) 会被忽略;如需自定义 Host(如测试或代理场景),应改用 req.Host = "custom.example.com"
  • Content-Length:自动计算并设置,手动设置将被覆盖
  • Connection、Transfer-Encoding、Trailer:由 Transport 控制,不应手动设置
  • date:默认自动添加;如需自定义,可先 Del("Date")Add("Date", ...)(需 RFC 1123 格式)

发送 JSON 请求的典型 Header 模式

调用 rest api 时,JSON 请求需明确声明内容类型和接受类型:

data := map[string]string{"name": "Alice"} jsonBytes, _ := json.Marshal(data)  req, _ := http.NewRequest("POST", "https://api.example.com/users", bytes.NewBuffer(jsonBytes)) req.Header.Set("Content-Type", "application/json")   // 必须 req.Header.Set("Accept", "application/json")         // 推荐 req.Header.Set("X-Request-ID", uuid.New().String())  // 自定义追踪头  resp, err := http.DefaultClient.Do(req)

基本上就这些。Header 操作本身不复杂,但要注意时机和限制——设早了、设错了、设了不该设的,都容易踩坑。保持简洁、按需设置、避开保留字段,就能稳定工作。

text=ZqhQzanResources