How to Implement Custom Middleware for Observability in Go

Implement Go observability middleware by wrapping your HTTP handler to log request methods, paths, and execution duration.

Implement custom observability middleware by wrapping your http.Handler to log request details and timing before and after the handler executes.

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

Apply it to your server using http.Handle or mux.Use:

mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello"))
})
http.ListenAndServe(":8080", LoggingMiddleware(mux))