User Tools

Site Tools


go:stdlib:http_server_struct

This is an old revision of the document!


http.Server

What is it?

`http.Server` is a configurable HTTP server type in Go’s `net/http` package. Compared to `http.ListenAndServe()`, it gives you more control: timeouts, graceful shutdown, TLS, limits, and logging.

What is it used for?

  • Run an HTTP server with production-friendly settings (timeouts).
  • Support graceful shutdown.
  • Serve HTTPS (TLS).
  • Customize server behavior (handler, error log, header limits).

Key fields (common)

  • `Addr`: address to listen on (e.g. `“:8080”`)
  • `Handler`: handler/router (e.g. `mux`). If `nil`, uses `http.DefaultServeMux`.
  • `ReadHeaderTimeout`: max time to read request headers
  • `ReadTimeout`: max time to read the entire request
  • `WriteTimeout`: max time allowed to write response
  • `IdleTimeout`: keep-alive idle time
  • `MaxHeaderBytes`: maximum size of request headers
  • `ErrorLog`: custom logger for server errors

Example: server with timeouts + graceful shutdown

package main
 
import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)
 
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })
 
    srv := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       10 * time.Second,
        WriteTimeout:      10 * time.Second,
        IdleTimeout:       60 * time.Second,
        MaxHeaderBytes:    1 << 20, // 1 MiB
    }
 
    // Start server
    go func() {
        log.Println("listening on", srv.Addr)
        err := srv.ListenAndServe()
        if err != nil && err != http.ErrServerClosed {
            log.Fatal(err)
        }
    }()
 
    // Wait for termination signal
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
    <-stop
 
    // Graceful shutdown
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
 
    log.Println("shutting down...")
    _ = srv.Shutdown(ctx)
    log.Println("server stopped")
}

Notes / pitfalls

  • `ListenAndServe()` blocks, so run it in a goroutine if you need shutdown logic.
  • Always set timeouts in production to reduce slow-client attacks.
  • `Shutdown(ctx)` waits for in-flight requests to finish (until the deadline).
  • `Close()` stops immediately (may drop connections).
  • If you use `nil` Handler, you’re using the global `http.DefaultServeMux`.

Hard words (English)

  • configurable /kənˈfɪɡjərəbəl/: cấu hình được
  • timeout /ˈtaɪmaʊt/: hết thời gian chờ
  • graceful shutdown /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt)
  • TLS /ˌtiː el ˈes/: bảo mật truyền tải (HTTPS)
  • limit /ˈlɪmɪt/: giới hạn
  • in-flight request /ɪn flaɪt rɪˈkwest/: request đang xử lý dở
  • deadline /ˈdedlaɪn/: hạn chót
  • drop /drɑːp/: cắt (ngắt) kết nối
  • attack /əˈtæk/: tấn công
  • goroutine /ˈɡoʊruːˌtiːn/: luồng nhẹ của Go
go/stdlib/http_server_struct.1767051238.txt.gz · Last modified: by phong2018