mux/middleware/request_id.go

37 lines
695 B
Go
Raw Permalink Normal View History

2024-07-29 02:38:17 +03:00
package middleware
import (
"context"
"net/http"
2024-09-17 01:19:25 +03:00
"go.neonxp.ru/mux/ctxlib"
2024-07-29 02:38:17 +03:00
"go.neonxp.ru/objectid"
)
const RequestIDHeader string = "X-Request-ID"
func RequestID(next http.Handler) http.Handler {
objectid.Seed()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get(RequestIDHeader)
if requestID == "" {
requestID = objectid.New().String()
}
2024-09-17 01:19:25 +03:00
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxlib.RequestID, requestID)))
2024-07-29 02:38:17 +03:00
})
}
func GetRequestID(r *http.Request) string {
2024-09-17 01:19:25 +03:00
rid := r.Context().Value(ctxlib.RequestID)
2024-07-29 02:38:17 +03:00
if rid == nil {
return ""
}
srid, ok := rid.(string)
if !ok {
return ""
}
return srid
}