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.go575 chars30 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.
gistlibby LogSnag