-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
78 lines (66 loc) · 1.65 KB
/
middleware.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
package main
import (
"flag"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
)
/**
* Clients is a shared data structure to keep track of clients connections by ip.
**/
type Clients struct {
mux *sync.RWMutex
ips map[string]*rate.Limiter
}
/**
* Flags for command line configuration.
**/
var (
max = flag.Uint("max", 10, "Maximum connections per client per second.")
burst = flag.Int("burst", 10, "Maximum burst size events.")
clients *Clients
)
/**
* init by parsing flags and creating shared data structure.
**/
func init() {
clients = &Clients{
mux: &sync.RWMutex{},
ips: make(map[string]*rate.Limiter),
}
}
/**
* rateLimit uses time/rate to test if a connection from given ip is allowed.
**/
func rateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
if !connectionAllowed(ip) {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
return
}
// Check if in testing environment
if !strings.HasSuffix(os.Args[0], ".test") {
// Generate a random number from 500 - 1500 to create fake process time
fake_process_time := rand.Intn(1500-500) + 500
time.Sleep(time.Millisecond * time.Duration(fake_process_time))
}
next.ServeHTTP(w, r)
})
}
/**
* connectionAllowed is a thread safe function that uses
* a shared data structure to access a rate limiter per ip.
**/
func connectionAllowed(ip string) bool {
clients.mux.Lock()
defer clients.mux.Unlock()
if _, ok := clients.ips[ip]; !ok {
clients.ips[ip] = rate.NewLimiter(rate.Limit(*max), *burst)
}
return clients.ips[ip].Allow()
}