Go by Example

HTTP Server

Configure http.Server timeouts for slow reads and idle connections, and account for WriteTimeout on streaming responses.

The net/http package serves requests through a handler. Construct an http.Server explicitly to set timeouts; the convenience ListenAndServe function uses no server timeouts.

A ServeMux routes requests to handlers. ReadHeaderTimeout bounds header reads, ReadTimeout bounds the full request including its body, WriteTimeout bounds response writes, and IdleTimeout bounds keep-alive idle time.

package main
 
import (
    "fmt"
    "net/http"
    "time"
)
 
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "ok")
    })
    server := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       10 * time.Second,
        WriteTimeout:      20 * time.Second,
        IdleTimeout:       60 * time.Second,
    }
    if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        panic(err)
    }
}

In production

Choose timeouts for the request sizes and response patterns your service supports; streaming endpoints may need different settings. Use server.Shutdown with a deadline during graceful shutdown so in-flight handlers can finish. Ensure handlers respect request context cancellation on slow operations.

Enjoyed this? Get more software craft delivered to your inbox.