How to Implement Logging Middleware in Go

Web
Wrap your HTTP handler in a function that logs request details before and after execution to implement logging middleware in Go.

Implement logging middleware by wrapping your http.Handler in a function that logs request details before and after execution.

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 with http.ListenAndServe(":8080", LoggingMiddleware(yourHandler)).