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请求通常将参数拼接在URL后。推荐使用url.Values构建查询字符串,避免手动拼接和编码错误。
示例代码:
package main
<p>import (
"fmt"
"io"
"net/http"
"net/url"
)</p><p>func main() {
// 构建查询参数
params := url.Values{}
params.Set("q", "golang http client")
params.Set("page", "1")</p><pre class="brush:php;toolbar:false;">// 拼接完整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语言免费学习笔记(深入)”;
提交表单类数据时,需设置Content-Type: application/x-www-form-urlencoded,并将键值对用url.Values编码后作为请求体。
http.PostForm可简化操作(自动设置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))向API发送结构化数据常用JSON格式。需手动序列化结构体、设置Content-Type: application/json,并传入bytes.NewReader作为请求体。
示例:
import (
"bytes"
"encoding/json"
"net/http"
)
<p>type User struct {
Name string <code>json:"name"</code>
Age int <code>json:"age"</code>
}</p><p>func postJSON() {
user := User{Name: "Bob", Age: 25}
jsonData, _ := json.Marshal(user)</p><pre class="brush:php;toolbar:false;">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,
}
<p>req, _ := http.NewRequest("GET", "<a href="https://www.php.cn/link/c19fa3728a347ac2a373dbb5c44ba1c2">https://www.php.cn/link/c19fa3728a347ac2a373dbb5c44ba1c2</a>", nil)
resp, err := client.Do(req) // 若服务响应超过5秒,此处返回timeout错误以上就是如何使用Golang实现HTTP客户端请求_发送GET和POST请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号