How do I add middleware to net/http handlers?

In Go, middleware can be added to `net/http` handlers to modify requests and responses, implement logging, authentication, or perform other tasks. Middleware functions allow you to wrap handlers so that you can easily add features to a web application.

Example of Middleware in Go

package main import ( "fmt" "net/http" ) // Middleware function that logs the requests func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("Request received:", r.Method, r.URL) next.ServeHTTP(w, r) // call the next handler }) } // Simple handler func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, World!") } func main() { // Create a new ServeMux mux := http.NewServeMux() mux.HandleFunc("/hello", helloHandler) // Wrap the mux with the logging middleware wrappedMux := loggingMiddleware(mux) // Start the server http.ListenAndServe(":8080", wrappedMux) }

middleware net/http handlers Go logging web application HTTP server