如何在Golang中使用net/http包构建HTTP客户端_Golang HTTP请求与响应

1次阅读

http.DefaultClient 发起最简 GET 请求需调用 http.Get 并检查 err,且必须 defer resp.Body.Close() 防止连接泄漏;生产环境应显式设置超时,推荐使用 &http.Client{Timeout: 10*time.Second};POST jsON 时需设 Content-Type、用 bytes.NewReader 包装数据,并检查 StatusCode 后再解码响应。

如何在Golang中使用net/http包构建HTTP客户端_Golang HTTP请求与响应

如何用 http.DefaultClient 发起最简 GET 请求

绝大多数场景下,不需要手动构造 http.Client,直接用 http.Gethttp.DefaultClient 就够了。它默认启用连接复用、带合理的超时(底层是无超时的,但实际使用中建议显式控制)。

常见错误是忽略返回的 Error,或没调用 resp.Body.Close() —— 这会导致连接泄漏,后续请求可能卡住或报 too many open files

  • http.Gethttp.DefaultClient.Get 的快捷封装,适合一次性简单请求
  • 必须检查 err:网络不通、dns 失败、TLS 握手失败都会在这里返回
  • 必须调用 resp.Body.Close(),哪怕你只读前几个字节
  • 响应体 resp.Bodyio.ReadCloser,可直接传给 json.NewDecoderio.copy
resp, err := http.Get("https://httpbin.org/get") if err != nil {     log.Fatal(err) } defer resp.Body.Close() // 注意:这里 defer 在函数退出时才执行,不是在 if 后立刻关 

body, _ := io.ReadAll(resp.Body) fmt.Printf("status: %s, body: %s", resp.Status, string(body))

如何设置超时和自定义 http.Client

http.DefaultClient 没有默认超时,一旦后端卡住或丢包,你的 goroutine 会无限等待。生产环境必须显式设置超时,且推荐用 &http.Client{Timeout: ...} 而非单独设 TransportTimeout,因为前者控制整个请求生命周期(Dial + TLS + Write + Read),后者只管底层连接。

  • Timeout 是总超时,覆盖从 DNS 解析到响应体读完的全过程
  • 若需更精细控制(如单独设连接超时、空闲连接超时),则需配置 http.Transport
  • 不要重复创建 http.Client:它是并发安全的,应复用;频繁新建会耗尽本地端口或触发 TIME_WaiT
  • 如果服务端返回 4xx/5xx,resp 仍非 nil,err 为 nil —— HTTP 状态码不触发错误
client := &http.Client{     Timeout: 10 * time.Second, } resp, err := client.Get("https://httpbin.org/delay/5") if err != nil {     // 可能是 context.DeadlineExceeded,也可能是 net.OpError     log.Printf("request failed: %v", err)     return } defer resp.Body.Close()

如何发送带 JSON 的 POST 请求并解析响应

发送结构化数据最常用的是 application/json,关键点在于:正确设置 Content-Type 头、用 bytes.NewReader 包装序列化后的字节、检查 resp.StatusCode 再解码。

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

  • 别用 http.Post 函数:它无法设 header,也不方便复用 client
  • json.Marshal 失败要提前处理,否则会发空体或 panic
  • 响应状态码不是 2xx 时,resp.Body 仍可能含错误详情(比如 {“error”:”invalid_token”}),别跳过读取
  • json.NewDecoder(resp.Body).Decode(&v)io.ReadAll + json.Unmarshal 更省内存
type Req struct{ Name string } type Resp struct{ Msg string } 

data, := json.Marshal(Req{Name: "gopher"}) req, := http.NewRequest("POST", "https://www.php.cn/link/dc076eb055ef5f8a60a41b6195e9f329", bytes.NewReader(data)) req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close()

if resp.StatusCode != 200 { log.Printf("unexpected status: %d", resp.StatusCode) return }

var result Resp if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { log.Fatal(err) }

如何处理重定向、cookie 和 HTTPS 证书问题

http.Client 默认自动跟随 301/302 重定向,最多 10 次;默认不保存 Cookie;HTTPS 默认校验证书。这三点在调试时最容易出意外。

  • 禁用重定向:设 CheckRedirect 返回 http.ErrUseLastResponse
  • 启用 Cookie:用 http.CookieJar标准库提供 cookiejar.New(nil)(注意传非 nil *cookiejar.Options 可控域名策略)
  • 跳过 HTTPS 证书校验(仅限测试):自定义 Transport.TLSClientConfig.InsecureSkipVerify = true,但务必确保只在开发环境启用
  • 自定义 Transport 后,记得把原有默认值(如 MaxIdleConns)一并设上,否则可能比默认更差

证书错误典型提示是 x509: certificate signed by unknown authoritynet/http: request canceled while waiting for connection(其实是 TLS 握手卡住)。这时候不要急着关校验,先确认系统根证书是否更新、目标站点是否用了私有 CA。

text=ZqhQzanResources