User Tools

Site Tools


go:stdlib:net_http

HTTP Server (net/http)

What is it?

An HTTP server is a program that listens on a network address (host:port) and serves HTTP requests by calling a handler.

In Go, the standard library package `net/http` provides everything you need to build a basic server.

What is it used for?

  • Build REST APIs and web services.
  • Serve pages, JSON responses, files, health checks.
  • Handle routing via `ServeMux` or a custom router.

Core building blocks

  • Handler: code that handles a request and writes a response.
    • `http.Handler` interface
    • `http.HandlerFunc` adapter
  • ResponseWriter: used to write status code, headers, and body.
  • Request: contains method, URL, headers, body, context, etc.
  • ServeMux: request multiplexer (router) that maps paths to handlers.
    • `http.DefaultServeMux` is the default global mux.

Minimal server (Hello + health)

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))
}

Production notes (important)

For production, you often use `http.Server` to set timeouts and graceful shutdown.

Example fields:

  • `ReadHeaderTimeout`
  • `ReadTimeout`
  • `WriteTimeout`
  • `IdleTimeout`

Hard words (English)

  • listen /ˈlɪsən/: lắng nghe (mở cổng nhận kết nối)
  • serve /sɝːv/: phục vụ request/response
  • handler /ˈhændlər/: bộ xử lý request
  • interface /ˈɪntərfeɪs/: giao diện (hợp đồng hàm)
  • adapter /əˈdæptər/: bộ chuyển/đệm để khớp kiểu
  • multiplexer (mux) /ˈmʌltɪˌpleksər/: bộ “chuyển tuyến”/gom chọn route
  • routing /ˈruːtɪŋ/: định tuyến
  • graceful shutdown /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt)
  • timeout /ˈtaɪmaʊt/: hết thời gian chờ
go/stdlib/net_http.txt · Last modified: by phong2018