How do I add middleware with Chi in Go?

In Go, when using the Chi router, you can easily add middleware to your routes. Middleware functions provide a way to intercept and process requests before they reach your handler or after the handler has executed. This is useful for tasks such as logging, authentication, and modifying requests or responses.

Here’s how you can add middleware to your Chi router:

package main import ( "net/http" "github.com/go-chi/chi/v5" ) // Middleware function for logging func Logger(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Log the request println("Request Method:", r.Method, "Request URL:", r.URL) next.ServeHTTP(w, r) }) } func main() { r := chi.NewRouter() // Use the middleware r.Use(Logger) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) }) http.ListenAndServe(":3000", r) }

This example defines a simple logging middleware that logs the request method and URL. The middleware is applied to the router, and any incoming requests will be processed by this middleware before reaching the handler.


Chi Go middleware logging HTTP router Go web development