章节

17.4 HTTP 客户端

本篇学习 Go HTTP 客户端的请求与响应读取流程,并能发送基础 GET 请求。

HTTP 客户端

概念说明

HTTP 客户端用于主动请求 HTTP 服务。
标准库中可以用 http.Get 发起简单 GET 请求,也可以用 http.Client 构造更复杂请求。

读取响应体后要及时关闭。
否则连接资源可能无法复用或释放。

语法/规则

  1. 使用 http.Get(url) 发起 GET 请求。
  2. 响应体在 resp.Body 中。
  3. 使用 defer resp.Body.Close() 关闭响应体。
  4. 使用 io.ReadAll(resp.Body) 一次性读取响应内容。
  5. 真实项目中应配置超时时间,避免请求无限等待。

HTTP 客户端示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 启动一个临时测试 HTTP 服务
		fmt.Fprintln(w, "hello client")
	}))
	defer server.Close()

	resp, err := http.Get(server.URL) // 向临时服务发起 GET 请求
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body) // 读取响应体全部内容
	if err != nil {
		panic(err)
	}

	fmt.Print(string(data))
}

输出结果:

1
hello client

常见错误

  1. 读取完响应后忘记关闭 resp.Body
  2. 使用默认客户端请求外部服务时没有设置超时。
  3. 只判断请求错误,不检查 HTTP 状态码。
  4. 多次读取同一个响应体,第二次通常已经没有数据可读。
本文禁止转载
使用 Hugo 构建
主题 StackJimmy 设计 由 Hobin 魔改
最近构建时间:2026-04-17 19:07:48 CST
载入天数...载入时分秒...
发表了 1 篇文章 · 发表了 152 篇笔记 · 总计 18 万 0 千字