User Tools

Site Tools


go:stdlib:http_server_struct

http.Server

What is it?

`http.Server` is the configurable HTTP server type in Go’s `net/http` package. It gives you more control than `http.ListenAndServe()` (timeouts, TLS, graceful shutdown, etc.).

What is it used for?

  • Run an HTTP server with production-ready settings (timeouts).
  • Support graceful shutdown.
  • Serve HTTPS (TLS).
  • Customize handler, error logger, max header size, etc.

Key fields (common)

  • `Addr`: address to listen on (e.g. `“:8080”`)
  • `Handler`: your router/handler (e.g. `mux`)
  • `ReadHeaderTimeout`: limit time to read request headers
  • `ReadTimeout`: total time to read request (headers + body)
  • `WriteTimeout`: time allowed to write response
  • `IdleTimeout`: keep-alive idle time
  • `ErrorLog`: custom logger
  • `MaxHeaderBytes`: limit request header size

Example: server with timeouts

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,
    }
 
    // Start server in background goroutine
    go func() {
        log.Println("listening on", srv.Addr)
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatal(err)
        }
    }()
 
    // Graceful shutdown on SIGINT/SIGTERM
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
    <-stop
 
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
 
    log.Println("shutting down...")
    _ = srv.Shutdown(ctx)
}

Notes / pitfalls

  • `ListenAndServe()` blocks; use a goroutine if you also need to handle shutdown signals.
  • Always set timeouts in production to reduce slowloris-style attacks.
  • Use `Shutdown(ctx)` for graceful shutdown; use `Close()` for immediate close.

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)
  • keep-alive /ˌkiːp əˈlaɪv/: giữ kết nối
  • slowloris /ˈsloʊˌlɔːrɪs/: kiểu tấn công giữ kết nối chậm
  • signal /ˈsɪɡnəl/: tín hiệu hệ điều hành
go/stdlib/http_server_struct.txt · Last modified: by phong2018