合并最新 main
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"github.com/baicai2026-baicai/goods/api/internal/adminstore"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/apikey"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/auth"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/clientip"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/gtin"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||
)
|
||||
@@ -31,6 +33,7 @@ type Handler struct {
|
||||
submitLimit *rateLimiter
|
||||
usage *ratelimit.Limiter
|
||||
cache cacheBumper
|
||||
clientIP *clientip.Resolver
|
||||
}
|
||||
|
||||
type cacheBumper interface {
|
||||
@@ -46,6 +49,7 @@ func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, sp
|
||||
basePath: basePath,
|
||||
spa: spa,
|
||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||
clientIP: clientip.Default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,11 +88,20 @@ func (h *Handler) invalidateCache(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Router builds the HTTP 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.Route(h.basePath, func(r chi.Router) {
|
||||
@@ -780,14 +793,8 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
// ---------- helpers ----------
|
||||
|
||||
func realIP(r *http.Request) string {
|
||||
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
|
||||
if i := strings.IndexByte(ip, ','); i >= 0 {
|
||||
return strings.TrimSpace(ip[:i])
|
||||
}
|
||||
return strings.TrimSpace(ip)
|
||||
}
|
||||
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
||||
return ip
|
||||
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
return host
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user