-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimiter.go
More file actions
39 lines (32 loc) · 874 Bytes
/
limiter.go
File metadata and controls
39 lines (32 loc) · 874 Bytes
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
package main
import (
"net/http"
"strings"
"github.com/tedyst/spotifyutils/api/utils"
"github.com/tedyst/spotifyutils/config"
"github.com/tedyst/spotifyutils/mapofmutex"
)
var limiters *mapofmutex.MapOfLimiter
func init() {
limiters = mapofmutex.NewMapOfLimiter()
}
func limitAPIRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the IP address for the current user.
ipAddress := r.RemoteAddr
fwdAddress := r.Header.Get("X-Forwarded-For")
if fwdAddress != "" {
ipAddress = fwdAddress
ips := strings.Split(fwdAddress, ", ")
if len(ips) > 1 {
ipAddress = ips[0]
}
}
if !limiters.Allow(ipAddress) && !*config.MockExternalCalls {
utils.ErrorString(w, r, "Too many requests")
w.WriteHeader(http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}