forked from mtusi2026/mtusi2026lab2
31 lines
590 B
Go
31 lines
590 B
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const requestIDKey contextKey = "request_id"
|
|
|
|
func RequestID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := uuid.NewString()
|
|
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
|
|
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
|
|
r = r.WithContext(ctx)
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func GetRequestID(ctx context.Context) string {
|
|
requestID, _ := ctx.Value(requestIDKey).(string)
|
|
return requestID
|
|
}
|