forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
42 lines (35 loc) · 867 Bytes
/
utils.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
package limiter
import (
"math/rand"
"net"
"net/http"
"strings"
"time"
)
// GetIP returns IP address from request.
func GetIP(r *http.Request) net.IP {
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
parts := strings.Split(ip, ",")
for i, part := range parts {
parts[i] = strings.TrimSpace(part)
}
return net.ParseIP(parts[0])
}
if ip := r.Header.Get("X-Real-IP"); ip != "" {
return net.ParseIP(ip)
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return net.ParseIP(r.RemoteAddr)
}
return net.ParseIP(host)
}
// GetIPKey extracts IP from request and returns hashed IP to use as store key.
func GetIPKey(r *http.Request) string {
return GetIP(r).String()
}
// Random return a random integer between min and max.
func Random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}