Files
trading_assistant/trading_assistant_api/common/httpx/request_id.go
2026-02-09 17:54:00 +08:00

48 lines
909 B
Go

package httpx
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strings"
)
type reqIDKey struct{}
func RequestID() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rid := incomingRID(r)
if rid == "" {
rid = genRID()
}
w.Header().Set("X-Request-ID", rid)
ctx := context.WithValue(r.Context(), reqIDKey{}, rid)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func RequestIDFromContext(r *http.Request) string {
v := r.Context().Value(reqIDKey{})
if s, ok := v.(string); ok {
return s
}
return ""
}
func incomingRID(r *http.Request) string {
h := r.Header.Get("X-Request-ID")
if h == "" {
h = r.Header.Get("X-Request-Id")
}
return strings.TrimSpace(h)
}
func genRID() string {
var b [16]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}