-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
57 lines (46 loc) · 1.14 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"net"
"net/http"
"strings"
"github.com/svenhertle/goddns/backends"
)
// GetIPDirect reads the client IP directly from the HTTP request.
func GetIPDirect(r *http.Request) string {
tmp := r.RemoteAddr // format: ip:port
// remove port
tmp = tmp[0:strings.LastIndex(tmp, ":")]
// remove "[" and "]" (for ipv6)
tmp = strings.Replace(tmp, "[", "", 1)
tmp = strings.Replace(tmp, "]", "", 1)
return tmp
}
// GetIPBehindProxy checks typical HTTP headers set by proxies for the client IP address.
func GetIPBehindProxy(r *http.Request) string {
// check the following headers
headers := []string{
"X-Forwarded-For",
"X-Real-IP",
}
for _, header := range headers {
value := r.Header.Get(header)
if value != "" {
// found, we ware done
return value
}
}
return ""
}
// CheckIP validates the IP address and returns its `AddressType` and whether it is valid or not.
func CheckIP(ip string) (backends.AddressType, bool) {
// parse IP
parsed := net.ParseIP(ip)
if parsed == nil {
return "", false
}
// get address type
if parsed.To4() != nil {
return backends.IPv4, true
}
return backends.IPv6, true
}