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