Golang如何发起带自定义请求头的POST请求
Golang如何发起带自定义请求头的POST请求 大家好,
我花了一些时间研究如何在 Go 语言中发送带有自定义请求头的 HTTP POST 请求。在朋友们的帮助和一些搜索之后,我找到了答案。我将在 Go Playground 上分享这段代码,希望它能对其他人有所帮助。
编辑: 根据 johandalabacka 和 Christophe_Meessen 的评论进行了改进 https://play.golang.org/p/P6Fxci-4HJv
func main() {
fmt.Println("hello world")
}
3 回复
我认为您不必将头部字段转换为小写 https://stackoverflow.com/a/5259004/7728251
更多关于Golang如何发起带自定义请求头的POST请求的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
另外需要注意的是,你应该在 ReadAll 之后关闭响应体:
resp, _ := client.Do(r)
if resp != nil {
defer resp.Body.Close()
}
body, err := ioutil.ReadAll(resp.Body)
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
// 1. 准备请求数据
data := map[string]interface{}{
"name": "John",
"email": "john@example.com",
}
jsonData, err := json.Marshal(data)
if err != nil {
panic(err)
}
// 2. 创建请求
req, err := http.NewRequest("POST", "https://httpbin.org/post", bytes.NewBuffer(jsonData))
if err != nil {
panic(err)
}
// 3. 设置自定义请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer your-token-here")
req.Header.Set("X-Custom-Header", "custom-value")
req.Header.Set("User-Agent", "MyGoApp/1.0")
// 4. 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// 5. 处理响应
fmt.Printf("Status: %s\n", resp.Status)
fmt.Printf("Status Code: %d\n", resp.StatusCode)
// 读取响应体
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Printf("Response Headers: %v\n", result["headers"])
}
更简洁的写法(使用 http.Post):
func main() {
data := map[string]interface{}{"name": "John"}
jsonData, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", "https://httpbin.org/post", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", "your-api-key")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
// 处理响应...
}
带超时设置的示例:
func main() {
data := map[string]interface{}{"test": "data"}
jsonData, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", "https://api.example.com/endpoint", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Request-ID", "12345")
// 设置10秒超时
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Request failed: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应...
}
这些示例展示了如何在Go中发送带自定义请求头的POST请求,包括设置认证头、自定义头和超时控制。

