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)).
Logging middleware is a small piece of code that sits between your web server and your actual request handlers. It automatically records details like the request method, URL, and how long the request took for every single request that comes in. Think of it like a security guard at a building entrance who writes down the name and time of every person entering, without stopping them from going to their destination.