middleware/request_id.go

36 lines
660 B
Go
Raw Permalink Normal View History

2024-04-06 20:05:14 +03:00
package middleware
import (
"context"
"net/http"
"go.neonxp.ru/objectid"
2024-04-06 20:05:14 +03:00
)
2024-07-28 19:32:33 +03:00
const RequestIDHeader string = "X-Request-ID"
2024-04-06 20:05:14 +03:00
2024-04-06 20:39:09 +03:00
func RequestID(next http.Handler) http.Handler {
objectid.Seed()
2024-04-06 20:05:14 +03:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get(RequestIDHeader)
if requestID == "" {
requestID = objectid.New().String()
2024-04-06 20:05:14 +03:00
}
2024-07-28 19:32:33 +03:00
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, requestID)))
2024-04-06 20:05:14 +03:00
})
}
func GetRequestID(r *http.Request) string {
2024-07-28 19:32:33 +03:00
rid := r.Context().Value(requestIDKey)
2024-04-06 20:05:14 +03:00
if rid == nil {
return ""
}
srid, ok := rid.(string)
if !ok {
return ""
}
return srid
}