User Tools

Site Tools


go:stdlib:http_server

This is an old revision of the document!


HTTP Server

What is it?

An HTTP server is a program (service) that:

  • listens on a network address (host:port), and
  • handles incoming HTTP requests, then
  • sends back HTTP responses.

In Go, you commonly build HTTP servers using the standard library package `net/http`.

What is it used for?

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

How it works (simple flow)

  1. Client (browser/app) sends an HTTP request (example: `GET /health`)
  2. Server receives the request
  3. Server calls a handler
  4. Handler writes an HTTP response (status code + headers + body)

Minimal example (Go net/http)

package main
 
import "net/http"
 
func main() {
    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })
 
    http.ListenAndServe(":8080", nil)
}

Key concepts

  • Handler: code that processes a request and writes a response.
  • ResponseWriter: used to write headers/status/body.
  • Request: contains method, URL, headers, body, context.
  • ServeMux (router): maps URL paths to handlers.

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)
  • handle /ˈhændəl/: xử lý
  • request /rɪˈkwest/: yêu cầu
  • response /rɪˈspɑːns/: phản hồi
  • status code /ˈsteɪtəs koʊd/: mã trạng thái (200, 404, 500…)
  • header /ˈhedər/: header (thông tin kèm theo)
  • body /ˈbɑːdi/: nội dung
  • router /ˈruːtər/: bộ định tuyến (map path → handler)
  • health check /helθ tʃek/: kiểm tra tình trạng
go/stdlib/http_server.1767050995.txt.gz · Last modified: by phong2018