在 Go 语言中,发送带自定义 Header 的 HTTP 请求可以使用标准库 net/http
。以下是几种常见场景的实现方式:
1. GET 请求带 Header
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://api.example.com/data"
// 创建请求对象
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// 设置 Header
req.Header.Add("Authorization", "Bearer your-token")
req.Header.Add("User-Agent", "MyGoApp/1.0")
req.Header.Set("Content-Type", "application/json") // Set会覆盖同名Header
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// 读取响应体
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
2. POST 请求带 Header(JSON Body)
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
url := "https://api.example.com/post"
// 构造 JSON Body
data := map[string]string{"key": "value"}
jsonData, _ := json.Marshal(data)
// 创建 Request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
panic(err)
}
// 设置 Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Add("X-API-Key", "your-api-key")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
fmt.Println("Status Code:", resp.StatusCode)
}
3. 直接使用 http.Get
/http.Post
(简化版)
如果需要简单快速发送带 Header 的请求,可以封装一个函数:
func GetWithHeader(url string, headers map[string]string) (string, error) {
req, _ := http.NewRequest("GET", url, nil)
for key, value := range headers {
req.Header.Add(key, value)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
return string(data), nil
}
// 调用示例:
headers := map[string]string{
"Authorization": "Bearer xyz",
"Accept": "application/json",
}
result, _ := GetWithHeader("https://api.example.com/data", headers)
关键点说明
Header.Add()
vsHeader.Set()
Add()
:追加值(允许多个相同 Key)。
Set()
:覆盖已有值(仅保留最新一个)。
默认 User-Agent
Go 的默认 User-Agent 是Go-http-client/1.1
,可以通过自定义 Header 修改。连接复用
- 推荐复用
http.Client{}
,而非每次创建新 Client。
- 推荐复用
错误处理
- 必须关闭 Response Body:使用
defer resp.Body.Close()
。
- 检查状态码:如
resp.StatusCode == http.StatusOK
。
- 必须关闭 Response Body:使用
HTTPS
- Go默认支持HTTPS,无需额外配置。
如果需要更复杂的场景(如文件上传、Cookie管理),可以进一步扩展逻辑!
内容由零声教学AI助手提供,问题来源于学员提问