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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?