===== 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 ==== * [[go:stdlib:http_server|HTTP server overview]] * [[go:stdlib:http_client_struct|http.Client]] * [[go:stdlib:http_server_struct|http.Server]] * [[go:concurrency:context|context.Context]] ==== 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)