ratelimitMiddleware.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package middleware
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "perms-system-server/internal/response"
  7. "github.com/zeromicro/go-zero/core/limit"
  8. "github.com/zeromicro/go-zero/core/stores/redis"
  9. "github.com/zeromicro/go-zero/rest/httpx"
  10. )
  11. type RateLimitMiddleware struct {
  12. limiter *limit.PeriodLimit
  13. }
  14. func NewRateLimitMiddleware(rds *redis.Redis, period int, quota int, keyPrefix string) *RateLimitMiddleware {
  15. limiter := limit.NewPeriodLimit(period, quota, rds, keyPrefix)
  16. return &RateLimitMiddleware{limiter: limiter}
  17. }
  18. func (m *RateLimitMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  19. return func(w http.ResponseWriter, r *http.Request) {
  20. ip := extractClientIP(r)
  21. key := fmt.Sprintf("ip:%s", ip)
  22. code, _ := m.limiter.Take(key)
  23. if code == limit.OverQuota {
  24. httpx.ErrorCtx(r.Context(), w, response.ErrTooManyRequests("请求过于频繁,请稍后再试"))
  25. return
  26. }
  27. next(w, r)
  28. }
  29. }
  30. func extractClientIP(r *http.Request) string {
  31. host, _, err := net.SplitHostPort(r.RemoteAddr)
  32. if err != nil {
  33. return r.RemoteAddr
  34. }
  35. return host
  36. }