make a http request with a custom header in go

You can create an http request with a custom header in go using the net/http package. Here's an example code snippet:

main.go
import (
    "net/http"
)

func main() {
    url := "https://example.com/api"
    
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        // handle error
    }
    
    req.Header.Set("Custom-Header", "header-value")
    
    client := &http.Client{}
    
    resp, err := client.Do(req)
    if err != nil {
        // handle error
    }
    
    defer resp.Body.Close()
}
395 chars
24 lines

In the code above, we create a new http.Request object with the NewRequest function and set the HTTP method to "GET" and the URL to "https://example.com/api". Then, we set a custom header with the Header.Set method. Finally, we make the HTTP request using an http.Client object and read the response body.

related categories

gistlibby LogSnag