Skip to content

Commit e7f3730

Browse files
committed
new file for various utilities
1 parent 88654ef commit e7f3730

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

utils.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"net"
6+
"net/http"
7+
"strings"
8+
)
9+
10+
func getIP(r *http.Request) string {
11+
// Check if the request was forwarded by a proxy (e.g. X-Forwarded-For header)
12+
// This is useful when behind a load balancer or reverse proxy
13+
ip := r.Header.Get("X-Forwarded-For")
14+
if ip == "" {
15+
ip = r.Header.Get("X-Real-Ip")
16+
}
17+
if ip != "" {
18+
// In case of multiple IPs in the X-Forwarded-For header, take the first one
19+
ips := strings.Split(ip, ",")
20+
return strings.TrimSpace(ips[0])
21+
}
22+
23+
// Otherwise, extract the IP from RemoteAddr
24+
ip, _, err := net.SplitHostPort(r.RemoteAddr)
25+
if err != nil {
26+
fmt.Println("Error parsing RemoteAddr:", err)
27+
return ""
28+
}
29+
return ip
30+
}

0 commit comments

Comments
 (0)