-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
143 lines (109 loc) · 2.73 KB
/
main.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type TokenBucket struct {
capacity int // capacity of the bucket
rate int // no of tokens to put into bucket every second.
tokens int // no of tokens
lastUpdated time.Time // keeps track of updated time
lock sync.Mutex
}
func (tb *TokenBucket) New(size int, rate int) {
tb.capacity = size
tb.rate = rate
tb.tokens = size
tb.lastUpdated = time.Now()
}
func (tb *TokenBucket) removeToken() bool {
tb.lock.Lock()
defer tb.lock.Unlock()
tb.refill()
if tb.tokens > 0 {
tb.tokens--
return true
} else {
return false
}
}
func (tb *TokenBucket) refill() {
elapsedTime := time.Now().Sub(tb.lastUpdated)
refillTokens := (int(elapsedTime.Seconds()) * tb.rate)
if refillTokens > 0 {
tb.lastUpdated = time.Now()
tb.tokens += refillTokens
}
if tb.tokens > tb.capacity {
tb.tokens = tb.capacity
}
}
func main() {
const port string = ":8080"
TBucket := TokenBucket{}
// Initialize token bucket
TBucket.New(5, 2)
done := make(chan bool)
go handleShutdowns(done)
log.Println("http server on port", port)
mux := http.NewServeMux()
mux.HandleFunc("/", homePage)
// Wrapped ratelimiter middleware
wrappedMux := rateLimiter(mux, &TBucket)
// server config
server := http.Server{
Addr: port,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 30 * time.Second,
Handler: wrappedMux,
}
// Start the server
go func() {
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}()
log.Println("Wating for shutdowns....")
<-done
log.Println("Shutting down")
}
func homePage(w http.ResponseWriter, r *http.Request) {
log.Println("Received request", r.Host)
w.Write([]byte("Home Page"))
}
// Rate limiter middleware
func rateLimiter(handler http.Handler, tb *TokenBucket) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
forwardRequest := tb.removeToken()
if !forwardRequest {
log.Println("Dropped request from: ", r.Host)
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte("429 - Too Many Requests!"))
return
}
handler.ServeHTTP(w, r)
})
}
// listens for shutdown signals
func handleShutdowns(done chan<- bool) {
signalChannel := make(chan os.Signal, 2)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGSEGV)
go func() {
sig := <-signalChannel
switch sig {
case os.Interrupt:
log.Println("Encountered os interrupt")
done <- true
case syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGSEGV:
log.Println("Received linux signel")
done <- true
}
}()
}