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()
}What the code does
The working surface is the functions loggingMiddleware and main — everything else is wiring.
Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts.
Applying it
Entry signature: func loggingMiddleware(next http.Handler) http.Handler
There are 1 call inside main — loggingMiddleware — executed top to bottom.
Statements that decide the outcome
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))
})
server.Shutdown(context.Background())
sigCh := make(chan os.Signal, 1)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- How do you run Go HTTP Server with Middleware?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.