Implement Request ID middleware by generating a unique ID for each request and storing it in the context before passing it to the next handler.
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := uuid.New().String()
ctx := context.WithValue(r.Context(), "requestID", id)
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Use this middleware in your server setup:
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
id := r.Context().Value("requestID").(string)
fmt.Fprintf(w, "Request ID: %s", id)
})
http.ListenAndServe(":8080", RequestIDMiddleware(mux))