Skip to content

Commit aa307cf

Browse files
committed
add GetIP func
1 parent f19376e commit aa307cf

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2024 Ayinke Ventures
3+
Copyright (c) 2025 Ayinke Ventures
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

ip.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package hermes
2+
3+
import (
4+
"net"
5+
"net/http"
6+
"strings"
7+
)
8+
9+
var (
10+
xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
11+
xRealIP = http.CanonicalHeaderKey("X-Real-IP")
12+
)
13+
14+
func GetIP(r *http.Request) net.IP {
15+
// cloudflare always prioritized
16+
cloudflareIP := r.Header.Get("CF-Connecting-IP")
17+
if cloudflareIP != "" {
18+
return net.ParseIP(cloudflareIP)
19+
}
20+
21+
if xff := r.Header.Get(xForwardedFor); xff != "" {
22+
i := strings.Index(xff, ", ")
23+
24+
if i == -1 {
25+
i = len(xff)
26+
}
27+
28+
return net.ParseIP(xff[:i])
29+
}
30+
31+
if ip := r.Header.Get(xRealIP); ip != "" {
32+
return net.ParseIP(ip)
33+
}
34+
35+
h, _, err := net.SplitHostPort(r.RemoteAddr)
36+
if err != nil {
37+
return net.IP{}
38+
}
39+
40+
return net.ParseIP(h)
41+
}

0 commit comments

Comments
 (0)