/
utils.go
34 lines (29 loc) · 906 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
package core
import (
"net"
"net/http"
"strings"
)
// https://stackoverflow.com/questions/37896931/how-to-limit-client-ip-address-when-using-golang-http-package
func GetRealAddr(r *http.Request) string {
remoteIP := ""
// the default is the originating ip. but we try to find better options because this is almost
// never the right IP
if parts := strings.Split(r.RemoteAddr, ":"); len(parts) == 2 {
remoteIP = parts[0]
}
// If we have a forwarded-for header, take the address from there
if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), ","); len(xff) > 0 {
addrs := strings.Split(xff, ",")
lastFwd := addrs[len(addrs)-1]
if ip := net.ParseIP(lastFwd); ip != nil {
remoteIP = ip.String()
}
// parse X-Real-Ip header
} else if xri := r.Header.Get("X-Real-Ip"); len(xri) > 0 {
if ip := net.ParseIP(xri); ip != nil {
remoteIP = ip.String()
}
}
return remoteIP
}