make a http request with a custom body as json in go

To make an HTTP request with a custom JSON body in Go, you can use the standard library http package along with the json package. Here's an example:

main.go
import (
    "bytes"
    "encoding/json"
    "net/http"
)

func main() {
    data := map[string]string{"key": "value"}
    jsonData, err := json.Marshal(data)
    if err != nil {
        // handle error
    }

    req, err := http.NewRequest("POST", "http://example.com/api", bytes.NewBuffer(jsonData))
    if err != nil {
        // handle error
    }

    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    // handle response
}
575 chars
30 lines

In this example, we first create a map containing the data we want to send. We then convert the map to JSON using the json.Marshal() function. This produces a byte slice containing the JSON-encoded data.

We then create an http.Request object using http.NewRequest(), passing in the HTTP method, URL, and the JSON-encoded body as a bytes.Buffer.

Next, we set the Content-Type header to application/json to indicate that the request body is in JSON format.

We create an http.Client object and use it to send the request with client.Do(). The response is returned in the resp variable.

Finally, we close the response body when we're done with it and handle the response data as needed.

related categories

gistlibby LogSnag