Table of Contents

http.Client

What is it?

`http.Client` is Go’s HTTP client used to send requests and receive responses. It supports connection pooling and keep-alive by default.

What is it used for?

Quick example (GET)

package main
 
import (
    "io"
    "log"
    "net/http"
    "time"
)
 
func main() {
    client := &http.Client{
        Timeout: 5 * time.Second,
    }
 
    resp, err := client.Get("https://example.com")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
 
    b, _ := io.ReadAll(resp.Body)
    log.Println("status:", resp.Status)
    log.Println("body bytes:", len(b))
}

Example (custom request + headers)

package main
 
import (
    "bytes"
    "log"
    "net/http"
    "time"
)
 
func main() {
    client := &http.Client{Timeout: 5 * time.Second}
 
    req, _ := http.NewRequest("POST", "https://example.com/api", bytes.NewBufferString(`{"a":1}`))
    req.Header.Set("Content-Type", "application/json")
 
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
 
    log.Println("status:", resp.StatusCode)
}

Notes / pitfalls (very important)

Hard words (English)