-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimit.go
55 lines (52 loc) · 1.15 KB
/
limit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package web
import (
"net/http"
"sync"
"time"
)
// RateLimit is a middleware which limits the frequency of access to the same IP address
func RateLimit(rate time.Duration) Handler {
var blackList sync.Map
return HandlerFunc(func(c *Context) {
remoteAddr := c.ClientIp()
if remoteAddr == "" {
c.Fail(http.StatusForbidden, "can not get client ip")
return
}
if _, ok := blackList.Load(remoteAddr); !ok {
blackList.Store(remoteAddr, struct{}{})
go func() {
time.Sleep(rate)
blackList.Delete(remoteAddr)
}()
} else {
c.Fail(http.StatusForbidden, "rate out of limit")
return
}
c.Next()
})
}
// TrafficLimit is a middleware which uses token bucket algorithm for traffic restriction
func TrafficLimit(tokenTotal int, rate time.Duration) Handler {
chg := make(chan struct{}, tokenTotal)
go func(ch chan<- struct{}) {
for i := 0; i < tokenTotal; i++ {
ch <- struct{}{}
}
for {
time.Sleep(rate)
ch <- struct{}{}
}
}(chg)
return HandlerFunc(func(c *Context) {
var ch <-chan struct{}
ch = chg
select {
case <-ch:
c.Next()
default:
c.Fail(http.StatusForbidden, "traffic congestion")
return
}
})
}