Implement the middleware pattern in Go by defining a function type that wraps http.Handler and chaining functions that modify the request or response before passing control to the next handler.
package main
import (
"log"
"net/http"
)
// Middleware is a function that wraps an http.Handler
func Middleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Pre-processing logic
log.Println("Before request")
// Call the next handler in the chain
handler.ServeHTTP(w, r)
// Post-processing logic
log.Println("After request")
})
}
func main() {
// Define your base handler
baseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
// Wrap the handler with middleware
finalHandler := Middleware(baseHandler)
// Start the server
log.Fatal(http.ListenAndServe(":8080", finalHandler))
}