-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
46 lines (36 loc) · 966 Bytes
/
ip.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
package otito
import (
"net/http"
"strings"
)
var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
var xRealIP = http.CanonicalHeaderKey("X-Real-IP")
type IPStrategy uint
const (
// CloudflareStrategy is used for apps running behind cloudflare
CloudflareStrategy IPStrategy = iota + 1
// Uses the standard X-Forwarded-For or X-Real-IP http header to find
// the ip
ForwardedOrRealIPStrategy
// please don't use this in prod. Maybe when running locally only
RemoteHeaderStrategy
)
func getIP(r *http.Request, strategy IPStrategy) string {
switch strategy {
case CloudflareStrategy:
return r.Header.Get(http.CanonicalHeaderKey("CF-Connecting-IP"))
case ForwardedOrRealIPStrategy:
if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ", ")
if i == -1 {
i = len(xff)
}
return xff[:i]
}
return r.Header.Get(xRealIP)
case RemoteHeaderStrategy:
return r.RemoteAddr
default:
return ""
}
}