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

在 Go 中设置 HTTP 请求头非常直接,核心是通过 *http.Request 的 Header 字段(类型为 http.Header,本质是 map[string][]string)进行操作。关键点在于:请求头必须在调用 http.Client.Do() 之前设置,且部分头(如 Host、Content-Length)由 Go 自动管理,手动设置可能被忽略或引发错误。
创建请求时即可预设常用头,这是最推荐的起点方式:
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...")若需对同一客户端发起多个不同头的请求,可在每次请求前修改 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)Go 的 http.Transport 会对某些头做自动处理。手动设置可能无效,甚至导致 panic 或静默失败:
立即学习“go语言免费学习笔记(深入)”;
Set("Host", ...) 会被忽略;如需自定义 Host(如测试或代理场景),应改用 req.Host = "custom.example.com"
Del("Date") 再 Add("Date", ...)(需 RFC 1123 格式)调用 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 操作本身不复杂,但要注意时机和限制——设早了、设错了、设了不该设的,都容易踩坑。保持简洁、按需设置、避开保留字段,就能稳定工作。
以上就是如何使用Golang设置HTTP请求Header_Golang HTTP Header处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号