-
Notifications
You must be signed in to change notification settings - Fork 2
/
realip.go
65 lines (54 loc) · 1.19 KB
/
realip.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
package realip
import (
"net"
"net/http"
"strings"
"github.com/valyala/fasthttp"
)
var headers = [...]string{
"X-Client-IP",
"X-Original-Forwarded-For",
"X-Forwarded-For",
"CF-Connecting-IP", // Cloudflare
"Fastly-Client-Ip", // Fastly CDN and Firebase hosting
"True-Client-Ip", // Akamai and Cloudflare
"X-Real-IP", // Nginx proxy/FastCGI
"X-Forwarded",
"Forwarded-For",
"Forwarded",
}
func FromRequest(ctx *fasthttp.RequestCtx) string {
if ctx == nil {
return ""
}
for _, h := range headers {
val := string(ctx.Request.Header.Peek(http.CanonicalHeaderKey(h)))
if strings.ContainsRune(val, ',') {
for _, address := range strings.Split(val, ",") {
address = strings.TrimSpace(address)
if isValidPublicAddress(address) {
return address
}
}
} else {
if isValidPublicAddress(val) {
return val
}
}
}
remoteAddr := ctx.RemoteAddr().String()
var remoteIP string
if strings.ContainsRune(remoteAddr, ':') {
remoteIP, _, _ = net.SplitHostPort(remoteAddr)
} else {
remoteIP = remoteAddr
}
return remoteIP
}
func isValidPublicAddress(addr string) bool {
ip := net.ParseIP(addr)
if ip == nil {
return false
}
return !IsPrivateIp(ip)
}