How to Write Reusable Middleware for net/http
Write a function that accepts an http.Handler and returns a new http.Handler wrapping it to execute logic before or after the request.
package main
import (
"fmt"
"net/http"
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Before:", r.URL.Path)
next.ServeHTTP(w, r)
fmt.Println("After:", r.URL.Path)
})
}
// Usage:
// http.Handle("/", LoggingMiddleware(myHandler))
func main() {
// Example usage
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
http.ListenAndServe(":8080", LoggingMiddleware(http.DefaultServeMux))
}