/
client_info.go
52 lines (43 loc) · 1.1 KB
/
client_info.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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package httpx
import (
"net"
"net/http"
"strings"
)
type GeoLocation struct {
City string
Region string
Country string
}
func GetClientIPAddressesWithoutInternalIPs(ipAddresses []string) (string, error) {
var res string
for i := len(ipAddresses) - 1; i >= 0; i-- {
ip := strings.TrimSpace(ipAddresses[i])
if !net.ParseIP(ip).IsPrivate() {
res = ip
break
}
}
return res, nil
}
func ClientIP(r *http.Request) string {
if trueClientIP := r.Header.Get("True-Client-IP"); trueClientIP != "" {
return trueClientIP
} else if realClientIP := r.Header.Get("X-Real-IP"); realClientIP != "" {
return realClientIP
} else if forwardedIP := r.Header.Get("X-Forwarded-For"); forwardedIP != "" {
ip, _ := GetClientIPAddressesWithoutInternalIPs(strings.Split(forwardedIP, ","))
return ip
} else {
return r.RemoteAddr
}
}
func ClientGeoLocation(r *http.Request) *GeoLocation {
return &GeoLocation{
City: r.Header.Get("Cf-Ipcity"),
Region: r.Header.Get("Cf-Region-Code"),
Country: r.Header.Get("Cf-Ipcountry"),
}
}