Listing 9.11: traceid middleware
June 24, 2025 ยท View on GitHub
Code in the file
Tip
Click the links to see the file and its directory in their original locations and state as they were at the time of the listing.
link / kit / traceid / http.go
package traceid
import "net/http"
// Middleware adds a new trace ID to [http.Request.Context].
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, ok := FromContext(r.Context()); !ok {
ctx := WithContext(r.Context(), New())
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}