Go 的 net/http 包提供简洁的 HTTP 请求方法:1. 简单 GET 用 http.Get;2. 自定义需求用 http.Client;3. POST 表单用 url.Values.Encode;4. POST JSON 用 json.Marshal 并设 Content-Type。
使用 Go 的 net/http 包发送 HTTP 请求非常简洁,无需第三方依赖。核心是 http.Client 和 http.NewRequest,GET 通常用快捷方法,POST 则需构造请求体。
对简单 GET,直接用 http.Get 最方便,它自动处理连接、重定向和基础错误:
*http.Response 和 error,记得检查错误并关闭响应体(resp.Body.Close())io.ReadAll 或 json.NewDecoder 解析resp, err := http.Get("https://httpbin.org/get")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
需要设置超时、代理、Header 或复用连接时,应显式创建 http.Client:
http.Client{Timeout: 10 * time.Second} 控制请求总时长req.Header.Set("User-Agent", "...") 添加请求头client.Do(req) 发送已构建的请求client := &http.Client{Timeout: 10 * time.Second}
req, _ := http.NewRequest("GET", "https://httpbin.org/get", nil)
req.Header.Set("User-Agent", "MyApp/1.0")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
提交 application/x-www-form-urlencoded 数据(如登录表单),推荐用 url.Values:
url.Values.Encode() 得到标准编码字符串Content-Type: application/x-www-form-urlencoded
strings.NewReader 传入 http.NewRequest
data := url.Values{"name": {"Alice"}, "age": {"30"}}
req, _ := http.NewRequest("POST", "https://www./link/dc076eb055ef5f8a60a41b6195e9f329", strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
向 API 提交 JSON,需序列化结构体并设置对应 Header:
json.Marshal 将 map 或 struct 转为字节切片Content-Type: application/json
bytes.NewReader(jsonBytes) 构造请求体payload := map[string]string{"title": "Hello", "content": "World"}
jsonBytes, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", "https://www./link/dc076eb055ef5f8a60a41b6195e9f329", bytes.NewReader(jsonBytes))
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()