乐闻世界logo
搜索文章和话题

How do i send a json string in a post request in go

7 个月前提问
3 个月前修改
浏览次数155

6个答案

1
2
3
4
5
6

在Go语言中,可以使用标准库net/http来发送HTTP POST请求,并且可以用encoding/json库来处理JSON数据。以下是如何发送包含JSON字符串的POST请求的一个步骤示例:

  1. 定义要发送的数据结构:首先定义一个与需要发送的JSON数据对应的Go结构体。
go
type MyData struct { Field1 string `json:"field1"` Field2 int `json:"field2"` }
  1. 创建JSON字符串:使用json.Marshal函数来将Go结构体转换成JSON字符串。
go
data := MyData{ Field1: "value1", Field2: 42, } jsonData, err := json.Marshal(data) if err != nil { // 处理错误情况 log.Fatalf("Error happened in JSON marshal. Err: %s", err) }
  1. 创建POST请求:使用http.NewRequest函数来创建一个POST请求,并将JSON字符串作为请求体。
go
url := "http://example.com/api/resource" req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { // 处理错误情况 log.Fatalf("Error occurred while creating HTTP request. Err: %s", err) }
  1. 添加请求头:设置HTTP请求头Content-Typeapplication/json,这表明正在发送的数据类型是JSON。
go
req.Header.Set("Content-Type", "application/json")
  1. 发送请求并处理响应:使用http.ClientDo方法发送请求,并处理服务器返回的响应。
go
client := &http.Client{} resp, err := client.Do(req) if err != nil { // 处理错误情况 log.Fatalf("Error occurred while sending the HTTP request. Err: %s", err) } defer resp.Body.Close() // 检查服务器响应的HTTP状态码是否为200 OK if resp.StatusCode == http.StatusOK { // 处理成功的情况,例如读取响应体 body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } else { // 处理服务器返回的错误 log.Printf("Server responded with a non-200 status code: %d", resp.StatusCode) }

上述代码展示了如何构建一个POST请求,其中包含JSON数据,并且发送该请求到服务器。在实际的编程实践中,通常还需要进行更多的错误检查和异常处理,以确保程序的健壮性。

2024年6月29日 12:07 回复

我不熟悉napping,但是使用 Golang 的net/http包效果很好(playground):

shell
func main() { url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>", url) var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) body, _ := io.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) }
2024年6月29日 12:07 回复

你可以只使用post发布你的json。

shell
values := map[string]string{"username": username, "password": password} jsonValue, _ := json.Marshal(values) resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))
2024年6月29日 12:07 回复

如果你已经有一个结构体。

shell
import ( "bytes" "encoding/json" "io" "net/http" "os" ) // ..... type Student struct { Name string `json:"name"` Address string `json:"address"` } // ..... body := &Student{ Name: "abc", Address: "xyz", } payloadBuf := new(bytes.Buffer) json.NewEncoder(payloadBuf).Encode(body) req, _ := http.NewRequest("POST", url, payloadBuf) client := &http.Client{} res, e := client.Do(req) if e != nil { return e } defer res.Body.Close() fmt.Println("response Status:", res.Status) // Print the body to the stdout io.Copy(os.Stdout, res.Body)

完整要点

2024年6月29日 12:07 回复

除了标准的 net/http 包之外,您还可以考虑使用我的GoRequest,它包装了 net/http,让您的生活更轻松,而无需过多考虑 json 或 struct。但您也可以在一个请求中混合搭配它们!(您可以在 gorequest github 页面中查看更多详细信息)

所以,最终你的代码将变成如下所示:

shell
func main() { url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>", url) request := gorequest.New() titleList := []string{"title1", "title2", "title3"} for _, title := range titleList { resp, body, errs := request.Post(url). Set("X-Custom-Header", "myvalue"). Send(`{"title":"` + title + `"}`). End() if errs != nil { fmt.Println(errs) os.Exit(1) } fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) fmt.Println("response Body:", body) } }

这取决于您想要如何实现。我创建这个库是因为我和你有同样的问题,我想要更短的代码,易于使用 json,并且在我的代码库和生产系统中更易于维护。

2024年6月29日 12:07 回复

http 或 https 的 post 请求示例

shell
//Encode the data postBody, _ := json.Marshal(map[string]string{ "name": "Test", "email": "Test@Test.com", }) responseBody := bytes.NewBuffer(postBody) //Leverage Go's HTTP Post function to make request resp, err := http.Post("https://postman-echo.com/post", "application/json", responseBody) //Handle Error if err != nil { log.Fatalf("An Error Occured %v", err) } defer resp.Body.Close() //Read the response body body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatalln(err) } sb := string(body) log.Printf(sb)
2024年6月29日 12:07 回复

你的答案