如何在Golang中发送POST请求_Golang HTTP POST请求实践

Go语言通过net/http包实现HTTP POST请求,支持JSON、表单提交及自定义头。2. 发送JSON数据需用json.Marshal序列化并设置Content-Type。3. 表单数据使用http.PostForm便捷方法。4. 自定义Header需用http.NewRequest配合Client.Do。5. 生产环境应设置超时避免阻塞。6. 注意错误处理与resp.Body.Close()资源释放。

在Go语言中发送HTTP POST请求非常简单,主要依赖标准库中的net/http包。无论是提交表单、上传JSON数据,还是处理API调用,都可以通过几行代码实现。下面介绍几种常见的POST请求使用场景和实践方法。

发送JSON格式的POST请求

现代Web API大多使用JSON作为数据交换格式。在Go中,你可以将结构体编码为JSON,并通过POST请求发送。

示例:

package main

import ( "bytes" "encoding/json" "fmt" "net/http" )

type User struct { Name string json:"name" Email string json:"email" }

func main() { user := User{ Name: "张三", Email: "zhangsan@example.com", }

jsonData, _ := json.Marshal(user)
resp, err := http.Post("https://www./link/dc076eb055ef5f8a60a41b6195e9f329", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
    fmt.Println("请求失败:", err)
    return
}
defer resp.Body.Close()

fmt.Println("状态码:", resp.StatusCode)

}

说明:使用json.Marshal将结构体转为JSON字节流,然后用bytes.NewBuffer包装成io.Reader,设置Content-Type为application/json

发送表单数据(application/x-www-form-urlencoded)

当你需要模拟浏览器提交表单时,应使用application/x-www-form-urlencoded格式。

data := url.Values{}
data.Set("username", "zhangsan")
data.Set("password", "123456")

resp, err := http.PostForm("https://www./link/dc076eb055ef5f8a60a41b6195e9f329", data) if err != nil { fmt.Println("请求失败:", err) return } defer resp.Body.Close()

fmt.Println("状态码:", resp.StatusCode)

http.PostForm是专门用于发送表单数据的便捷方法,会自动设置正确的Content-Type。

自定义请求头与手动构建请求

如果需要添加自定义Header(如Authorization),就不能再使用http.PostPostForm这类快捷方法,而要手动创建http.Request

req, err := http.NewRequest("POST", "https://www./link/dc076eb055ef5f8a60a41b6195e9f329", bytes.NewBuffer(jsonData))
if err != nil {
    fmt.Println(err)
    return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer your-token-here")

client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("请求失败:", err) return } defer resp.Body.Close()

fmt.Println("响应状态:", resp.Status)

这种方法灵活性更高,适用于需要认证、自定义超时、Cookie等复杂场景。

设置超时时间避免阻塞

生产环境中必须设置超时,防止请求长时间挂起。

client := &http.Client{
    Timeout: 10 * time.Second,
}
resp, err := client.Do(req)

建议始终为HTTP客户端设置合理的超时时间,比如5到30秒,具体根据接口性能调整。

基本上就这些。Go的标准库足够强大,无需引入第三方包就能完成大多数HTTP操作。只要掌握http.Posthttp.PostFormhttp.NewRequest这几种方式,就能应对绝大多数POST请求场景。不复杂但容易忽略的是错误处理和资源释放——记得检查err并调用resp.Body.Close()