What Is Middleware in Go and How to Write It

Web
Go middleware is a function wrapping an http.Handler to intercept and modify requests or responses before they reach the final handler.

Middleware in Go is a function that wraps an http.Handler to modify the request before it reaches the handler or the response after it returns. It implements the http.Handler interface by calling ServeHTTP, allowing you to chain logic like logging, authentication, or compression around your core business logic.

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))
    })
}

// Usage
http.Handle("/", LoggingMiddleware(http.HandlerFunc(myHandler)))