make a http post request in go

In Go, making an HTTP POST request can be achieved using the net/http package. Here is an example of how to make an HTTP POST request in Go:

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

func main() {
    url := "http://example.com/submit"
    data := []byte(`{"name":"John Doe","age":30}`)

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
    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
}
484 chars
26 lines

In this example, we first create a http.NewRequest with the URL and request body as parameters. We then set the request header to indicate that the request body is in JSON format.

Finally, we use a http.Client to send the request and receive the response. The response body can then be read and processed as needed.

Note that in this example we are specifying the request body as a JSON string, but the same approach can be used for other types of request bodies such as form data.

related categories

gistlibby LogSnag