How to perform an HTTP POST request with JSON data in Go?

To perform an HTTP POST request with JSON data in Go, you can use the net/http package and json package. Here's an example:

package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { // Create the JSON data user := User{ Name: "John Doe", Email: "[email protected]", } jsonData, err := json.Marshal(user) if err != nil { fmt.Println("Error marshaling JSON:", err) return } // Send the HTTP request resp, err := http.Post("https://example.com/api/users", "application/json", bytes.NewBuffer(jsonData)) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() // Process the response fmt.Println("Response status:", resp.Status) // ... }

In this example, we define a struct User that represents the JSON data we want to send. We then create an instance of User with some sample data.

We use the json.Marshal function to convert the User object into JSON data. If there is any error during marshaling, we handle it accordingly.

Then, we use the http.Post function to send the HTTP POST request. We pass the URL, content type header ("application/json"), and a bytes.Buffer containing the JSON data as the request body.

The response is stored in the resp variable. Make sure to close the response body after you're done with it.

Finally, you can process the response as needed. In this example, we simply print the response status, but you can access the response body and headers as well.