add rate limiting configuration for authenticated and unauthenticated requests
All checks were successful
Build & Publish Docker Image / build-and-push (push) Successful in 55s

This commit is contained in:
Flavio Fois
2026-03-24 08:56:05 +01:00
parent 9d4a1b7ef3
commit 4fb3290cf6
8 changed files with 155 additions and 84 deletions

View File

@@ -5,8 +5,20 @@ import (
"strconv"
"strings"
"sync"
"time"
)
type RateLimitConfig struct {
UnauthMaxReqs int
UnauthWindow time.Duration
UnauthMaxFails int
UnauthBanDur time.Duration
AuthMaxReqs int
AuthWindow time.Duration
AuthMaxFails int
AuthBanDur time.Duration
}
type Config struct {
Port string
DSN string
@@ -16,6 +28,7 @@ type Config struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime int
RateLimit RateLimitConfig
}
var (
@@ -85,5 +98,33 @@ func load() *Config {
MaxOpenConns: maxOpenConns,
MaxIdleConns: maxIdleConns,
ConnMaxLifetime: connMaxLifetime,
RateLimit: RateLimitConfig{
UnauthMaxReqs: envInt("RL_UNAUTH_MAX_REQS", 10),
UnauthWindow: envDuration("RL_UNAUTH_WINDOW", 5*time.Minute),
UnauthMaxFails: envInt("RL_UNAUTH_MAX_FAILS", 5),
UnauthBanDur: envDuration("RL_UNAUTH_BAN_DUR", 15*time.Minute),
AuthMaxReqs: envInt("RL_AUTH_MAX_REQS", 100),
AuthWindow: envDuration("RL_AUTH_WINDOW", time.Minute),
AuthMaxFails: envInt("RL_AUTH_MAX_FAILS", 20),
AuthBanDur: envDuration("RL_AUTH_BAN_DUR", 5*time.Minute),
},
}
}
func envInt(key string, fallback int) int {
if s := os.Getenv(key); s != "" {
if n, err := strconv.Atoi(s); err == nil {
return n
}
}
return fallback
}
func envDuration(key string, fallback time.Duration) time.Duration {
if s := os.Getenv(key); s != "" {
if d, err := time.ParseDuration(s); err == nil {
return d
}
}
return fallback
}