Echo errors, middleware and handlers used three different formats (message object, error object, bare string). One error handler now writes all of them the same way; status codes are unchanged.
30 lines
978 B
Go
30 lines
978 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"music-server/internal/logging"
|
|
|
|
"github.com/labstack/echo/v5"
|
|
echoMiddleware "github.com/labstack/echo/v5/middleware"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// RateLimit allows each client IP limit requests per window, with bursts up to limit.
|
|
func RateLimit(limit int, window time.Duration) echo.MiddlewareFunc {
|
|
config := echoMiddleware.DefaultRateLimiterConfig
|
|
config.Store = echoMiddleware.NewRateLimiterMemoryStoreWithConfig(echoMiddleware.RateLimiterMemoryStoreConfig{
|
|
Rate: float64(limit) / window.Seconds(),
|
|
Burst: limit,
|
|
ExpiresIn: window,
|
|
})
|
|
config.DenyHandler = func(c *echo.Context, identifier string, err error) error {
|
|
logging.GetLogger().Warn("Rate limit exceeded",
|
|
zap.String("ip", identifier),
|
|
zap.String("path", c.Request().URL.Path))
|
|
return echo.NewHTTPError(http.StatusTooManyRequests, "Rate limit exceeded. Please try again later.")
|
|
}
|
|
return echoMiddleware.RateLimiterWithConfig(config)
|
|
}
|