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:
- Define the Data Structure to Send:First, define a Go struct that corresponds to the JSON data you want to send.
gotype MyData struct { Field1 string `json:"field1"` Field2 int `json:"field2"` }
- Create the JSON String:Use the
json.Marshalfunction to convert the Go struct into a JSON string.
godata := 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) }
- Create the POST Request:Use
http.NewRequestto create a POST request, with the JSON string as the request body.
gourl := "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) }
- Add Request Headers:Set the
Content-Typeheader toapplication/jsonto indicate that the data being sent is JSON.
goreq.Header.Set("Content-Type", "application/json")
- Send the Request and Handle the Response:Use the
Domethod ofhttp.Clientto send the request and handle the server's response.
goclient := &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.