make a http request with a custom body in go

To make an HTTP request with a custom body in Go, you can use the built-in net/http package. Here is an example of making a POST request with a JSON body:

main.go
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

func main() {
    // Define the data to send in the body
    data := map[string]string{
        "username": "johndoe",
        "password": "password123",
    }
    payload, err := json.Marshal(data)
    if err != nil {
        panic(err)
    }

    // Create a new request with the payload as the body
    req, err := http.NewRequest("POST", "https://your-api-endpoint.com", bytes.NewBuffer(payload))
    if err != nil {
        panic(err)
    }

    // Set the Content-Type header to JSON
    req.Header.Set("Content-Type", "application/json")

    // Send the request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    // Handle the response
    defer resp.Body.Close()
    // ...
}
818 chars
40 lines

In this example, the data variable is a map of strings that we want to send as a JSON payload. We first marshal the data to create a JSON byte slice.

We then create a new http.Request with the POST method and the payload as the body, set the Content-Type header to application/json, and send the request with an http.Client. The response is then handled as desired.

related categories

gistlibby LogSnag