-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxytrust.go
35 lines (28 loc) · 953 Bytes
/
proxytrust.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
package proxytrust
import (
"net"
"net/http"
"strings"
)
//TrustProxyClientIp detect real client ip address if the code is on the server behind non-anonymous proxy or balancer
func TrustProxyClientIp(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
remoteAddr := removePort(req.RemoteAddr)
if xForwardedFor := req.Header.Get("X-Forwarded-For"); xForwardedFor != "" {
xForwardedFor = removePort(strings.TrimSpace(strings.Split(xForwardedFor, ",")[0]))
if xForwardedFor != "" && net.ParseIP(xForwardedFor) != nil {
remoteAddr = xForwardedFor
}
} else if xRealIp := req.Header.Get("X-Real-IP"); xRealIp != "" {
xRealIp = removePort(xRealIp)
if xRealIp != "" && net.ParseIP(xRealIp) != nil {
remoteAddr = xRealIp
}
}
req.RemoteAddr = remoteAddr
next.ServeHTTP(res, req)
})
}
func removePort(ip string) string {
return strings.Split(ip, ":")[0]
}