-
Notifications
You must be signed in to change notification settings - Fork 34
/
util.go
42 lines (35 loc) · 1.04 KB
/
util.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 httpx
import (
"net"
"net/http"
"strings"
)
func ClientIP(r *http.Request) string {
clientIP := ClientIPByHeaderForwardedFor(r.Header.Get(HeaderForwardedFor))
if clientIP != "" {
return clientIP
}
clientIP = ClientIPByHeaderRealIP(r.Header.Get(HeaderRealIP))
if clientIP != "" {
return clientIP
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
// ClientIPByHeaderForwardedFor
// X-Forwarded-For: client, proxy1, proxy2
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
func ClientIPByHeaderForwardedFor(headerForwardedFor string) string {
if index := strings.IndexByte(headerForwardedFor, ','); index >= 0 {
return headerForwardedFor[0:index]
}
return strings.TrimSpace(headerForwardedFor)
}
// ClientIPByHeaderRealIP
// X-Forwarded-For: client, proxy1, proxy2
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
func ClientIPByHeaderRealIP(headerRealIP string) string {
return strings.TrimSpace(headerRealIP)
}