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

To make a HTTP request with a custom body as text in Go, you can follow these steps:

  1. Create a http.Client object.

  2. Create a http.NewRequest object, specifying the method, URL, and request body as a io.Reader object.

  3. Set any additional headers on the request object.

  4. Use the http.Client object to execute the request and get a http.Response object.

  5. Read the response body and do any processing required.

Here's an example:

main.go
package main

import (
    "fmt"
    "net/http"
    "strings"
)

func main() {
    // Create a http.Client object.
    client := http.Client{}
    
    // Create a request body as a string.
    requestBody := "This is a custom request body."
    
    // Create a http.NewRequest object with POST method, URL, and request body.
    req, err := http.NewRequest(http.MethodPost, "https://example.com/api", strings.NewReader(requestBody))
    if err != nil {
        panic(err)
    }
    
    // Set additional headers on the request.
    req.Header.Set("Content-Type", "text/plain")
    
    // Use the http.Client object to execute the request.
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    
    // Read the response body.
    responseBody, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    
    fmt.Println(string(responseBody))
}
893 chars
39 lines

related categories

gistlibby LogSnag