File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments