In Go, middleware can be added to `net/http` handlers to modify requests and responses, implement logging, authentication, or perform other tasks. Middleware functions allow you to wrap handlers so that you can easily add features to a web application.
package main
import (
"fmt"
"net/http"
)
// Middleware function that logs the requests
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Request received:", r.Method, r.URL)
next.ServeHTTP(w, r) // call the next handler
})
}
// Simple handler
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
func main() {
// Create a new ServeMux
mux := http.NewServeMux()
mux.HandleFunc("/hello", helloHandler)
// Wrap the mux with the logging middleware
wrappedMux := loggingMiddleware(mux)
// Start the server
http.ListenAndServe(":8080", wrappedMux)
}
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?