Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add a component to support rate limt control #29

Merged
merged 6 commits into from
Jul 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions server/internal/middleware/frequency_control.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package middleware

import (
"sync"
"time"

"github.com/gin-gonic/gin"
)

// define rate limit struct
type frequencyControlByTokenBucket struct {
refreshRate float64 // 令牌的刷新速率
capacity int64 // bucket's capacity
tokens float64 // tokens' count
lastToken time.Time //latest time token stored
mtx sync.Mutex // mutex
}

// allow frequency
func (tb *frequencyControlByTokenBucket) Allow() bool {
tb.mtx.Lock()
defer tb.mtx.Unlock()
now := time.Now()
// compute tokens which needs
tb.tokens = tb.tokens + tb.refreshRate*now.Sub(tb.lastToken).Seconds()
if tb.tokens > float64(tb.capacity) {
tb.tokens = float64(tb.capacity)
}
// judge weather to pass through
if tb.tokens >= 1 {
tb.tokens--
tb.lastToken = now
return true
}

return false
}

// LimitHandler registried a middle ware to use
func LimitHandler(maxConn int, refreshRate float64) gin.HandlerFunc {
tb := &frequencyControlByTokenBucket{
capacity: int64(maxConn),
refreshRate: refreshRate,
tokens: 0,
lastToken: time.Now(),
}
return func(c *gin.Context) {
if !tb.Allow() {
c.String(503, "Too many request")
c.Abort()

return
}
c.Next()
}
}