跳转到主内容
极星编程网:以代码为星,赴技术山海!

如何在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.php.cn/link/dc076eb055ef5f8a60a41b6195e9f329", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
    fmt.Println("请求失败:", err)
    return
}
defer resp.Body.Close()

fmt.Println("状态码:", resp.StatusCode)
}立即学习“go语言免费学习笔记(深入)”; 说明:使用
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.php.cn/link/dc076eb055ef5f8a60a41b6195e9f329", data) if err != nil { fmt.Println("请求失败:", err) return } defer resp.Body.Close()

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

Comet AI 浏览器

下载 Comet AI 浏览器,体验由 Perplexity AI 驱动的革命性上网方式。内置 AI 助手可实时总结网页、跨标签页对比信息、自动执行任务。告别繁琐操作,让 AI 成为你的浏览副驾,大幅提升研究与工作效率。支持 Windows、macOS、Android 和 iOS。

下载
http.PostForm
是专门用于发送表单数据的便捷方法,会自动设置正确的Content-Type。 自定义请求头与手动构建请求 如果需要添加自定义Header(如Authorization),就不能再使用
http.Post
或
PostForm
这类快捷方法,而要手动创建
http.Request
。
req, err := http.NewRequest("POST", "https://www.php.cn/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.Post
、
http.PostForm
和
http.NewRequest
这几种方式,就能应对绝大多数POST请求场景。不复杂但容易忽略的是错误处理和资源释放——记得检查err并调用
resp.Body.Close()
。

相关文章