User Tools

Site Tools


go:stdlib:http_server

HTTP Server (net/http)

What is it?

An HTTP server is a program (service) that:

  • listens on an address (host:port),
  • accepts incoming HTTP connections/requests,
  • runs a handler to process each request,
  • writes an HTTP response (status + headers + body).

In Go, the standard library package `net/http` provides everything needed to build an HTTP server.

What is it used for?

  • Build REST APIs and microservices.
  • Serve web pages, JSON, files, webhooks.
  • Provide health checks (e.g. `/health`) for monitoring/load balancers.

Core building blocks

  • Handler: processes requests and writes responses
    • `http.Handler` (interface)
    • `http.HandlerFunc` (function adapter)
  • ResponseWriter: writes status code, headers, and body.
  • Request: method, URL, headers, body, context.
  • ServeMux (router): maps URL paths to handlers
    • `http.DefaultServeMux` is the default global mux.
    • `http.NewServeMux()` creates a dedicated mux.

Minimal server (custom mux)

package main
 
import (
    "log"
    "net/http"
)
 
func main() {
    mux := http.NewServeMux()
 
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello"))
    })
 
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })
 
    log.Println("listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Common patterns

  • Default mux pattern (quick demos): use `http.HandleFunc` + `ListenAndServe(…, nil)`
  • Custom mux pattern (recommended): `mux := http.NewServeMux()` and pass it to server
  • Middleware pattern: wrap handlers (logging, auth, recover, rate limit)

Production notes (important)

For production, prefer `http.Server{…}` with timeouts and graceful shutdown. Time-outs help protect against slow-client attacks and avoid hanging connections.

Hard words (English)

  • server /ˈsɝːvər/: máy chủ / dịch vụ phục vụ
  • service /ˈsɝːvɪs/: dịch vụ
  • listen /ˈlɪsən/: lắng nghe (mở cổng nhận kết nối)
  • accept /əkˈsept/: chấp nhận kết nối/nhận vào
  • handler /ˈhændlər/: bộ xử lý request
  • interface /ˈɪntərfeɪs/: giao diện (hợp đồng)
  • adapter /əˈdæptər/: bộ chuyển/đệm để khớp kiểu
  • router /ˈruːtər/: bộ định tuyến (map path → handler)
  • multiplexer (mux) /ˈmʌltɪˌpleksər/: bộ chọn route theo đường dẫn
  • webhook /ˈwebhʊk/: callback qua HTTP
  • load balancer /ˈloʊd ˌbælənser/: cân bằng tải
  • middleware /ˈmɪdəlwer/: lớp trung gian (bọc handler)
  • graceful shutdown /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm
  • timeout /ˈtaɪmaʊt/: hết thời gian chờ
  • hanging /ˈhæŋɪŋ/: treo/chờ mãi
go/stdlib/http_server.txt · Last modified: by phong2018