User Tools

Site Tools


go:stdlib:http_client_struct

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?

  • Call external APIs (GET/POST/PUT/DELETE).
  • Set timeouts and transport options.
  • Reuse connections efficiently.

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)

  • Always `defer resp.Body.Close()` to avoid leaking connections.
  • Prefer a reusable `http.Client` (do not create a new client per request in hot code).
  • Set `Timeout` (or use request context) to avoid hanging forever.
  • For advanced control, customize `Transport` (proxy, TLS settings, connection limits).

Hard words (English)

  • request /rɪˈkwest/: yêu cầu
  • response /rɪˈspɑːns/: phản hồi
  • connection pooling /kəˈnekʃən ˈpuːlɪŋ/: gom/tái sử dụng kết nối
  • reuse /ˌriːˈjuːz/: tái sử dụng
  • leak /liːk/: rò rỉ (tài nguyên)
  • hang /hæŋ/: treo, chờ mãi
  • transport /ˈtrænspɔːrt/: tầng vận chuyển (cấu hình cách client kết nối)
go/stdlib/http_client_struct.txt · Last modified: by phong2018