-
Notifications
You must be signed in to change notification settings - Fork 22
/
helpers.go
77 lines (70 loc) · 1.58 KB
/
helpers.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package khatru
import (
"net"
"net/http"
"strconv"
"strings"
"github.com/nbd-wtf/go-nostr"
)
func isOlder(previous, next *nostr.Event) bool {
return previous.CreatedAt < next.CreatedAt ||
(previous.CreatedAt == next.CreatedAt && previous.ID > next.ID)
}
func getServiceBaseURL(r *http.Request) string {
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Host
}
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
if host == "localhost" {
proto = "http"
} else if strings.Index(host, ":") != -1 {
// has a port number
proto = "http"
} else if _, err := strconv.Atoi(strings.ReplaceAll(host, ".", "")); err == nil {
// it's a naked IP
proto = "http"
} else {
proto = "https"
}
}
return proto + "://" + host
}
var privateMasks = func() []net.IPNet {
privateCIDRs := []string{
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}
masks := make([]net.IPNet, len(privateCIDRs))
for i, cidr := range privateCIDRs {
_, netw, err := net.ParseCIDR(cidr)
if err != nil {
return nil
}
masks[i] = *netw
}
return masks
}()
func isPrivate(ip net.IP) bool {
for _, mask := range privateMasks {
if mask.Contains(ip) {
return true
}
}
return false
}
func GetIPFromRequest(r *http.Request) string {
if xffh := r.Header.Get("X-Forwarded-For"); xffh != "" {
for _, v := range strings.Split(xffh, ",") {
if ip := net.ParseIP(strings.TrimSpace(v)); ip != nil && ip.IsGlobalUnicast() && !isPrivate(ip) {
return ip.String()
}
}
}
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}