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

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

4个答案

1
2
3
4

In Go, you can use the standard library net/http to send HTTP POST requests and the encoding/json package to handle JSON data. Below is a step-by-step example of how to send a POST request containing a JSON string:

  1. Define the Data Structure to Send:First, define a Go struct that corresponds to the JSON data you want to send.
go
type MyData struct { Field1 string `json:"field1"` Field2 int `json:"field2"` }
  1. Create the JSON String:Use the json.Marshal function to convert the Go struct into a JSON string.
go
data := MyData{ Field1: "value1", Field2: 42, } jsonData, err := json.Marshal(data) if err != nil { // Handle error cases log.Fatalf("Error occurred in JSON marshaling. Err: %s", err) }
  1. Create the POST Request:Use http.NewRequest to create a POST request, with the JSON string as the request body.
go
url := "http://example.com/api/resource" req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { // Handle error cases log.Fatalf("Error occurred while creating the HTTP request. Err: %s", err) }
  1. Add Request Headers:Set the Content-Type header to application/json to indicate that the data being sent is JSON.
go
req.Header.Set("Content-Type", "application/json")
  1. Send the Request and Handle the Response:Use the Do method of http.Client to send the request and handle the server's response.
go
client := &http.Client{} resp, err := client.Do(req) if err != nil { // Handle error cases log.Fatalf("Error occurred while sending the HTTP request. Err: %s", err) } defer resp.Body.Close() // Check if the server's HTTP status code is 200 OK if resp.StatusCode == http.StatusOK { // Handle success cases, e.g., read the response body body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } else { // Handle server errors log.Printf("Server responded with a non-200 status code: %d", resp.StatusCode) }

The above code demonstrates how to construct a POST request containing JSON data and send it to the server. In practical programming scenarios, additional error checking and exception handling are often required to ensure the program's robustness.

2024年6月29日 12:07 回复

Example of HTTP or HTTPS POST requests

go
//Marshal the data postBody, _ := json.Marshal(map[string]string{ "name": "Test", "email": "Test@Test.com", }) responseBody := bytes.NewBuffer(postBody) //Use Go's HTTP Post function to make the request resp, err := http.Post("https://postman-echo.com/post", "application/json", responseBody) //Handle Errors if err != nil { log.Fatalf("An Error Occurred %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 回复

In addition to the standard net/http package, you can also consider using my GoRequest, which wraps net/http to simplify your workflow without having to worry too much about JSON or structs. However, you can also mix and match them in a single request! (You can find more details on the Gorequest GitHub page.)

Therefore, your final code will look like this:

go
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) } }

This depends on how you want to implement it. I created this library because I had the same problem as you—I wanted shorter code, easier JSON usage, and better maintainability in my codebase and production systems.

2024年6月29日 12:07 回复

You can use the POST method to send your JSON.

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

你的答案