Go HTTP Server with Middleware
Create a production-ready HTTP server in Go with middleware chaining, graceful shutdown, request logging, CORS handling, and context-based timeouts. Uses.
Code
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "{\"status\": \"ok\"}")
})
server := &http.Server{Addr: ":8080", Handler: loggingMiddleware(mux)}
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
<-sigCh
server.Shutdown(context.Background())
}()
server.ListenAndServe()
}