How to Handle Cross-Cutting Concerns in Go (Logging, Metrics, Auth)

Wrap HTTP handlers with middleware functions to centrally manage logging, authentication, and metrics in Go applications.

Handle cross-cutting concerns in Go by wrapping http.Handler with middleware functions that execute before and after the target handler.

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 AuthMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Authorization") == "" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/api", handleAPI)

    handler := LoggingMiddleware(AuthMiddleware(mux))
    http.ListenAndServe(":8080", handler)
}