Implement request logging middleware by creating a function that wraps an existing http.Handler, logs request details before calling the next handler, and returns the wrapped handler.
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
Use it by wrapping your server's handler chain:
mux := http.NewServeMux()
mux.HandleFunc("/", handler)
log.Println("Server starting...")
log.Fatal(http.ListenAndServe(":8080", LoggingMiddleware(mux)))