31. Go: HTTP Server with Graceful Shutdown
GoHandling requests with context.Context propagation and safe shutdown.
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
http.ListenAndServe(":8080", mux)
}
When to use
The foundation of any HTTP service in Go — a starting point for building an API or microservice.
Common pitfalls
This example doesn't handle actual graceful shutdown (catching the SIGTERM signal) — in production you need to add signal handling and http.Server.Shutdown().