mirror of https://github.com/synctv-org/synctv
Feat: rate limit
parent
f9844dd58e
commit
73ccad0718
@ -0,0 +1,19 @@
|
||||
package conf
|
||||
|
||||
type RateLimitConfig struct {
|
||||
Enable bool `yaml:"enable" lc:"default: false" env:"SERVER_RATE_LIMIT_ENABLE"`
|
||||
Period string `yaml:"period" env:"SERVER_RATE_LIMIT_PERIOD"`
|
||||
Limit int64 `yaml:"limit" env:"SERVER_RATE_LIMIT_LIMIT"`
|
||||
TrustForwardHeader bool `yaml:"trust_forward_header" lc:"default: false" hc:"it will configure the limiter to trust X-Real-IP and X-Forwarded-For headers. Please be advised that using this option could be insecure (ie: spoofed) if your reverse proxy is not configured properly to forward a trustworthy client IP." env:"SERVER_TRUST_FORWARD_HEADER"`
|
||||
TrustedClientIPHeader string `yaml:"trusted_client_ip_header" hc:"will configure the limiter to use a custom header to obtain user IP. Please be advised that using this option could be insecure (ie: spoofed) if your reverse proxy is not configured properly to forward a trustworthy client IP." env:"SERVER_TRUSTED_CLIENT_IP_HEADER"`
|
||||
}
|
||||
|
||||
func DefaultRateLimitConfig() RateLimitConfig {
|
||||
return RateLimitConfig{
|
||||
Enable: false,
|
||||
Period: "1m",
|
||||
Limit: 300,
|
||||
TrustForwardHeader: false,
|
||||
TrustedClientIPHeader: "",
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/synctv-org/synctv/server/model"
|
||||
limiter "github.com/ulule/limiter/v3"
|
||||
mgin "github.com/ulule/limiter/v3/drivers/middleware/gin"
|
||||
"github.com/ulule/limiter/v3/drivers/store/memory"
|
||||
)
|
||||
|
||||
func NewLimiter(Period time.Duration, Limit int64, options ...limiter.Option) gin.HandlerFunc {
|
||||
limit := limiter.New(memory.NewStore(), limiter.Rate{
|
||||
Period: Period,
|
||||
Limit: Limit,
|
||||
}, options...)
|
||||
return mgin.NewMiddleware(limit, mgin.WithLimitReachedHandler(func(c *gin.Context) {
|
||||
c.JSON(http.StatusTooManyRequests, model.NewApiErrorStringResp("too many requests"))
|
||||
}))
|
||||
}
|
||||
Loading…
Reference in New Issue