Go标准库net/http提供简洁高效的HTTP客户端支持,可直接发送GET/POST请求;需正确构造Request、设置Header、处理请求体并关闭响应体;推荐用url.Values编码参数,POST表单用PostForm,JSON数据需手动序列化并设Content-Type;生产环境必须配置超时。

Go语言标准库 net/http 提供了简洁、高效、线程安全的HTTP客户端支持,无需额外依赖即可发送GET和POST请求。关键在于正确构造http.Request、设置必要的Header(如Content-Type)、处理请求体(尤其是POST),并及时关闭响应体。
发送GET请求(带查询参数)
GET请求通常将参数拼接在URL后。推荐使用url.Values构建查询字符串,避免手动拼接和编码错误。
示例代码:
package mainimport ( "fmt" "io" "net/http" "net/url" )
func main() { // 构建查询参数 params := url.Values{} params.Set("q", "golang http client") params.Set("page", "1")
// 拼接完整URL baseURL := "https://httpbin.org/get" fullURL := baseURL + "?" + params.Encode() // 发起GET请求 resp, err := http.Get(fullURL) if err != nil { panic(err) } defer resp.Body.Close() // 必须关闭响应体,防止连接泄漏 // 读取响应内容 body, _ := io.ReadAll(resp.Body) fmt.Println(string(body))}
立即学习“go语言免费学习笔记(深入)”;
发送POST请求(表单数据 application/x-www-form-urlencoded)
提交表单类数据时,需设置Content-Type: application/x-www-form-urlencoded,并将键值对用url.Values编码后作为请求体。
- 使用
http.PostForm可简化操作(自动设置Header和编码) - 若需更多控制(如自定义Header、超时),建议用
http.NewRequest+http.DefaultClient.Do
示例(使用PostForm):
resp, err := http.PostForm("https://httpbin.org/post", url.Values{
"name": {"Alice"},
"age": {"30"},
})
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))发送POST请求(JSON数据 application/json)
向API发送结构化数据常用JSON格式。需手动序列化结构体、设置Content-Type: application/json,并传入bytes.NewReader作为请求体。
示例:
import (
"bytes"
"encoding/json"
"net/http"
)
type User struct {
Name string json:"name"
Age int json:"age"
}
func postJSON() {
user := User{Name: "Bob", Age: 25}
jsonData, _ := json.Marshal(user)
req, _ := http.NewRequest("POST", "https://httpbin.org/post", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))}
立即学习“go语言免费学习笔记(深入)”;
添加超时与自定义客户端
生产环境中必须设置超时,避免请求无限阻塞。通过http.Client配置Timeout或更精细的Transport参数。
-
Timeout:整个请求(连接+读写)的总时限 -
Transport中可单独控制IdleConnTimeout、TLSHandshakeTimeout等
示例(带5秒超时):
client := &http.Client{
Timeout: 5 * time.Second,
}
req, _ := http.NewRequest("GET", "https://www.php.cn/link/c19fa3728a347ac2a373dbb5c44ba1c2", nil)
resp, err := client.Do(req) // 若服务响应超过5秒,此处返回timeout错误










