Micro-service for file storage and processing written in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
940 B

  1. package middlewares
  2. import (
  3. "net/http"
  4. "github.com/throttled/throttled/store/memstore"
  5. "github.com/throttled/throttled/v2"
  6. )
  7. type RateLimiterMiddleware struct {
  8. rateLimiter throttled.HTTPRateLimiter
  9. }
  10. func (middleware RateLimiterMiddleware) Middleware(next http.Handler) http.Handler {
  11. return middleware.rateLimiter.RateLimit(next)
  12. }
  13. func CreateRateLimiterMiddleware(requestsPerMinute int, allowedBurst int) (*RateLimiterMiddleware, error) {
  14. store, err := memstore.New(65536)
  15. if err != nil {
  16. return nil, err
  17. }
  18. quota := throttled.RateQuota{
  19. MaxRate: throttled.PerMin(requestsPerMinute),
  20. MaxBurst: allowedBurst,
  21. }
  22. rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
  23. if err != nil {
  24. return nil, err
  25. }
  26. httpRateLimiter := throttled.HTTPRateLimiter{
  27. RateLimiter: rateLimiter,
  28. VaryBy: &throttled.VaryBy{Path: true},
  29. }
  30. return &RateLimiterMiddleware{
  31. rateLimiter: httpRateLimiter,
  32. }, nil
  33. }