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.

GoData Fetching

Code

snippet
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

FAQ

How do you run Go HTTP Server with Middleware?
Just run the file; everything it needs ships with the runtime itself.