forked from mtusi2026/mtusi2026lab3
36 lines
883 B
Go
36 lines
883 B
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const RequestIDKey contextKey = "request_id"
|
|
|
|
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
|
func RequestID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
reqID := r.Header.Get("X-Request-Id")
|
|
if reqID == "" {
|
|
reqID = uuid.NewString()
|
|
}
|
|
|
|
w.Header().Set("X-Request-Id", reqID)
|
|
|
|
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// GetRequestID достает ID запроса из контекста
|
|
func GetRequestID(ctx context.Context) string {
|
|
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
|
return val
|
|
}
|
|
return uuid.NewString()
|
|
}
|