How to use net http Client

Use http.Client to send requests, customize settings like timeout, and always close response bodies for proper connection reuse.

Use http.Client to send HTTP requests by creating a client instance and calling its Get or Do methods. The default client handles connection pooling and keep-alives automatically, but you can customize behavior by setting fields like Timeout or Transport.

resp, err := http.Get("https://example.com")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()
// Process response

For custom configurations like timeouts or specific transport settings, create a new client:

client := &http.Client{
    Timeout: 5 * time.Second,
}
resp, err := client.Get("https://example.com")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

To send POST requests with a body, use http.NewRequest and client.Do:

req, err := http.NewRequest("POST", "https://example.com/api", strings.NewReader("data"))
if err != nil {
    log.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

If you need to disable HTTP/2 (e.g., for compatibility with buggy servers), set the GODEBUG environment variable before running your program:

export GODEBUG=http2client=0

Or configure the transport explicitly in code:

client := &http.Client{
    Transport: &http.Transport{
        ForceAttemptHTTP2: false,
    },
}

Always close the response body with defer resp.Body.Close() to ensure connections are reused properly.