go:stdlib:http_client
This is an old revision of the document!
Table of Contents
HTTP Client (net/http)
What is it?
An HTTP client is code that sends HTTP requests to a server and reads HTTP responses back.
In Go, the standard library package `net/http` provides:
- helper functions like `http.Get`, `http.Post`, and
- the configurable client type `http.Client`.
What is it used for?
- Call external REST APIs.
- Send webhooks.
- Download/upload data over HTTP/HTTPS.
- Communicate between microservices.
Core building blocks
- Client: performs requests (`Do`, `Get`, `Post`).
- Request: method, URL, headers, body, context.
- Response: status, headers, body.
- Transport: controls connection pooling, proxies, TLS, timeouts (advanced).
Minimal example (GET)
package main import ( "io" "log" "net/http" ) func main() { resp, err := http.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("bytes:", len(b)) }
Best practices (important)
- Always `defer resp.Body.Close()` to avoid leaking connections.
- Reuse an `http.Client` for many requests (do not create a new one every time).
- Use timeouts (client timeout or request context) to avoid hanging forever.
- Validate status codes before trusting the response body.
Related pages
Hard words (English)
- client /ˈklaɪənt/: phía gọi (bên gửi request)
- request /rɪˈkwest/: yêu cầu
- response /rɪˈspɑːns/: phản hồi
- leak /liːk/: rò rỉ (tài nguyên/kết nối)
- reuse /ˌriːˈjuːz/: tái sử dụng
- timeout /ˈtaɪmaʊt/: hết thời gian chờ
- hanging /ˈhæŋɪŋ/: treo/chờ mãi
- transport /ˈtrænspɔːrt/: tầng vận chuyển (cách kết nối HTTP)
- pooling /ˈpuːlɪŋ/: gom/tái sử dụng (kết nối)
go/stdlib/http_client.1767051432.txt.gz · Last modified: by phong2018
