Files
glchat/internal/httpx/context.go
T

46 lines
1.3 KiB
Go
Raw Normal View History

package httpx
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
)
func newRequestID() string {
var buf [16]byte
if _, err := rand.Read(buf[:]); err != nil {
return "0000000000000000"
}
return hex.EncodeToString(buf[:])
}
type requestInfoKey struct{}
// RequestInfo — данные исходного запроса, нужные сервисам (IP, User-Agent).
type RequestInfo struct {
IP string
UserAgent string
}
// WithRequestInfo кладёт данные запроса в контекст (используется HTTP-слоем).
func WithRequestInfo(ctx context.Context, r *http.Request) context.Context {
return context.WithValue(ctx, requestInfoKey{}, RequestInfo{
IP: ClientIP(r, nil),
UserAgent: r.Header.Get("User-Agent"),
})
}
func requestInfo(ctx context.Context) RequestInfo {
if info, ok := ctx.Value(requestInfoKey{}).(RequestInfo); ok {
return info
}
return RequestInfo{}
}
// ClientIPFromContext возвращает IP клиента для контекста huma.
func ClientIPFromContext(ctx context.Context) string { return requestInfo(ctx).IP }
// UserAgentFromContext возвращает User-Agent для контекста huma.
func UserAgentFromContext(ctx context.Context) string { return requestInfo(ctx).UserAgent }