fix(api): 仅信任配置的反向代理转发客户端 IP (#39)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 00:44:04 +00:00
co-authored by Devin AI
parent 36f9c95fa7
commit 667e6d0f00
11 changed files with 373 additions and 15 deletions
+13 -1
View File
@@ -16,6 +16,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
"github.com/baicai2026-baicai/goods/api/internal/store"
)
@@ -57,6 +58,7 @@ type Handler struct {
store *store.Store
spa fs.FS
limiter *ratelimit.Limiter
clientIP *clientip.Resolver
anonLimit int
anonTotalQuota int64
regRatePerMin int
@@ -69,6 +71,7 @@ func New(s *store.Store, spa fs.FS) *Handler {
return &Handler{
store: s,
spa: spa,
clientIP: clientip.Default(),
anonLimit: defaultAnonLimit,
anonTotalQuota: defaultAnonTotalQuota,
regRatePerMin: defaultRegRatePerMin,
@@ -87,6 +90,15 @@ func (h *Handler) WithRateLimit(l *ratelimit.Limiter, anonPerMin int) *Handler {
return h
}
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
if resolver == nil {
resolver = clientip.Default()
}
h.clientIP = resolver
return h
}
// WithQuotas configures the cumulative free quota for anonymous callers and the
// per-minute rate + cumulative quota self-registered keys receive. Non-positive
// values keep the defaults.
@@ -107,7 +119,7 @@ func (h *Handler) WithQuotas(anonTotal, regPerMin, regTotal int) *Handler {
func (h *Handler) Router() http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(h.clientIP.Middleware)
r.Use(middleware.Recoverer)
r.Get("/healthz", h.Healthz)