下面是一个使用Golang发送POST请求的示例代码,你可以根据自己的需求进行修改:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Request struct {
Action int `json:"action"`
Domain string `json:"domain"`
ProductCode string `json:"product_code"`
Origin []Origin `json:"origin"`
}
type Origin struct {
Role string `json:"role"`
Port int `json:"port"`
Origin string `json:"origin"`
Weight int `json:"weight"`
}
func main() {
url := "http://example.com/your-endpoint" // 替换成你的目标URL
data := Request{
Action: 1,
Domain: "aaa.com",
ProductCode: "008",
Origin: []Origin{
{
Role: "master",
Port: 80,
Origin: "1.1.1.1",
Weight: 10,
},
},
}
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("JSON编码失败:", err)
return
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("创建请求失败:", err)
return
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("发送请求失败:", err)
return
}
defer resp.Body.Close()
fmt.Println("响应状态码:", resp.StatusCode)
}
请注意替换url变量为你要发送POST请求的目标URL。另外,还需要根据实际情况修改JSON数据的结构和字段内容。
内容由零声教学AI助手提供,问题来源于学员提问




