In Go, adding a request ID middleware is a common practice to help track requests across multiple services. This middleware generates a unique ID for every incoming HTTP request and attaches it to the request context. This allows for easier debugging and monitoring.
Go Middleware, Request ID, HTTP Server, Golang, Logging
This article explains how to implement request ID middleware in Go applications to enhance request tracing and debugging.
package main
import (
"context"
"log"
"math/rand"
"net/http"
"time"
)
// Middleware to add a request ID
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Generate a unique request ID
requestID := rand.Uint64()
// Add the request ID to the context
ctx := context.WithValue(r.Context(), "requestID", requestID)
r = r.WithContext(ctx)
// Log the request ID
log.Printf("Request ID: %d", requestID)
// Call the next handler
next.ServeHTTP(w, r)
})
}
func main() {
http.Handle("/", RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})))
log.Println("Starting server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
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?