47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type ctxKey string
|
|
|
|
const (
|
|
requestIDKey ctxKey = "request_id"
|
|
userKey ctxKey = "user"
|
|
tokenKey ctxKey = "token"
|
|
)
|
|
|
|
func requestIDFrom(r *http.Request) string {
|
|
if v, ok := r.Context().Value(requestIDKey).(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func withRequestID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.Header.Get("X-Request-Id")
|
|
if id == "" {
|
|
id = uuid.NewString()
|
|
}
|
|
w.Header().Set("X-Request-Id", id)
|
|
ctx := context.WithValue(r.Context(), requestIDKey, id)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// withInstanceID ставит X-Instance-Id на КАЖДЫЙ ответ (включая ошибки и health).
|
|
// ID генерируется один раз при старте процесса — стабилен в пределах жизни.
|
|
func withInstanceID(instanceID string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", instanceID)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|