How do I add request ID middleware in Go?

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)) }

Go Middleware Request ID HTTP Server Golang Logging