在 Golang 中,可以使用 http.Client 客户端来实现复用访问服务端的 HTTP 连接。默认情况下,http.Client 会自动进行连接的复用。
package main
import (
"fmt"
"net/http"
)
func main() {
client := &http.Client{}
request, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
response, err := client.Do(request)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer response.Body.Close()
// 处理响应...
}
通过上述代码,你可以创建一个 http.Client 实例,并且多次使用该实例发送请求。这样,底层的连接将会被自动复用,在多次访问中不会重复创建连接。需要注意的是,在每次请求后,一定要确保关闭响应体(response body)以释放资源。
此外,你还可以设置 Transport 的参数来控制连接池的大小等配置:
transport := &http.Transport{
MaxIdleConns: 10, // 最大空闲连接数
IdleConnTimeout: time.Second * 30, // 空闲连接超时时间
DisableKeepAlives: false, // 是否禁用 keep-alive,默认为 false(启用 keep-alive)
}
client := &http.Client{
Transport: transport,
}
// 发送请求...
通过调整 MaxIdleConns 和 IdleConnTimeout 等参数,你可以对连接池的行为进行进一步的配置和优化。
内容由零声教学AI助手提供,问题来源于学员提问




