Table of Contents

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?

Key fields (common)

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

Hard words (English)