You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

frequency_control.go 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright © 2023 OpenIM open source community. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package middleware
  15. import (
  16. "sync"
  17. "time"
  18. "github.com/gin-gonic/gin"
  19. )
  20. // define rate limit struct.
  21. type frequencyControlByTokenBucket struct {
  22. refreshRate float64 // token refresh rate
  23. capacity int64 // bucket capacity
  24. tokens float64 // token count
  25. lastToken time.Time // latest time token stored
  26. mtx sync.Mutex // mutex
  27. }
  28. // allow frequency.
  29. func (tb *frequencyControlByTokenBucket) Allow() bool {
  30. tb.mtx.Lock()
  31. defer tb.mtx.Unlock()
  32. now := time.Now()
  33. // compute tokens which needs
  34. tb.tokens = tb.tokens + tb.refreshRate*now.Sub(tb.lastToken).Seconds()
  35. if tb.tokens > float64(tb.capacity) {
  36. tb.tokens = float64(tb.capacity)
  37. }
  38. // judge weather to pass through
  39. if tb.tokens >= 1 {
  40. tb.tokens--
  41. tb.lastToken = now
  42. return true
  43. }
  44. return false
  45. }
  46. // LimitHandler registried a middle ware to use.
  47. func LimitHandler(maxConn int, refreshRate float64) gin.HandlerFunc {
  48. tb := &frequencyControlByTokenBucket{
  49. capacity: int64(maxConn),
  50. refreshRate: refreshRate,
  51. tokens: 0,
  52. lastToken: time.Now(),
  53. }
  54. return func(c *gin.Context) {
  55. if !tb.Allow() {
  56. c.String(503, "Too many request")
  57. c.Abort()
  58. return
  59. }
  60. c.Next()
  61. }
  62. }