-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrequest_limit.go
69 lines (57 loc) · 1.29 KB
/
request_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"io"
"net/http"
"sync"
"time"
)
type RequestLimitService struct {
Interval time.Duration
MaxCount int
Lock sync.Mutex
ReqCount int
}
func NewRequestLimitService(interval time.Duration, maxCnt int) *RequestLimitService {
reqLimit := &RequestLimitService{
Interval: interval,
MaxCount: maxCnt,
}
go func() {
ticker := time.NewTicker(interval)
for {
<-ticker.C
reqLimit.Lock.Lock()
fmt.Println("Reset Count...")
reqLimit.ReqCount = 0
reqLimit.Lock.Unlock()
}
}()
return reqLimit
}
func (reqLimit *RequestLimitService) Increase() {
reqLimit.Lock.Lock()
defer reqLimit.Lock.Unlock()
reqLimit.ReqCount += 1
}
func (reqLimit *RequestLimitService) IsAvailable() bool {
reqLimit.Lock.Lock()
defer reqLimit.Lock.Unlock()
return reqLimit.ReqCount < reqLimit.MaxCount
}
var RequestLimit = NewRequestLimitService(10 * time.Second, 5)
func helloHandler(w http.ResponseWriter, r *http.Request) {
if RequestLimit.IsAvailable() {
RequestLimit.Increase()
fmt.Println(RequestLimit.ReqCount)
io.WriteString(w, "Hello world!\n")
} else {
fmt.Println("Reach request limiting!")
io.WriteString(w, "Reach request limit!\n")
}
}
func main() {
fmt.Println("Server Started!")
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8000", nil)
}