To create and use middleware in a Go web application, you can follow these steps:
import (
"net/http"
"log"
)
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Code for middleware logic goes here
log.Println("Executing middleware")
// Call the next handler
next.ServeHTTP(w, r)
})
}
func handler(w http.ResponseWriter, r *http.Request) {
// Code for handling the request goes here
log.Println("Executing handler")
}
ServeMux
and register the middleware and handler functions:func main() {
mux := http.NewServeMux()
// Use the middleware for all requests
mux.Handle("/", middleware(http.HandlerFunc(handler)))
// Start the server
log.Println("Starting server on port 8080")
http.ListenAndServe(":8080", mux)
}
http://localhost:8080
to see the logs for the middleware and handler functions.Note: The middleware function can be used for any custom logic that needs to be executed before or after handling a request, such as authentication, logging, error handling, etc. You can add additional middleware functions by chaining them in the ServeMux
registration.