File tree 3 files changed +19
-24
lines changed
3 files changed +19
-24
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,11 @@ package httputil
3
3
import (
4
4
"io"
5
5
"net/http"
6
+ "strings"
7
+ )
8
+
9
+ const (
10
+ headerXForwardedFor = "X-Forwarded-For"
6
11
)
7
12
8
13
// CloseResponse closes the response's body. But reads at least some of the body so if it's
@@ -15,3 +20,13 @@ func CloseResponse(resp *http.Response) {
15
20
resp .Body .Close ()
16
21
}
17
22
}
23
+
24
+ func GetRequestIP (req * http.Request ) string {
25
+ addresses := strings .Split (req .Header .Get (headerXForwardedFor ), "," )
26
+ if addresses [0 ] == "" {
27
+ splits := strings .Split (req .RemoteAddr , ":" )
28
+ return strings .Join (splits [:len (splits )- 1 ], ":" ) // When there is no load-balancer
29
+ }
30
+
31
+ return strings .ReplaceAll (addresses [0 ], " " , "" )
32
+ }
Original file line number Diff line number Diff line change 1
- package ip_test
1
+ package httputil_test
2
2
3
3
import (
4
4
"net/http"
5
5
"testing"
6
6
7
7
"github.com/stretchr/testify/require"
8
8
9
- kitip "github.com/rudderlabs/rudder-go-kit/ip "
9
+ "github.com/rudderlabs/rudder-go-kit/httputil "
10
10
)
11
11
12
- func TestIPFromReq (t * testing.T ) {
12
+ func TestGetRequestIP (t * testing.T ) {
13
13
testCases := []struct {
14
14
name string
15
15
headerValue string
@@ -42,7 +42,7 @@ func TestIPFromReq(t *testing.T) {
42
42
Header : http.Header {"X-Forwarded-For" : {testCase .headerValue }},
43
43
RemoteAddr : testCase .remoteAddr ,
44
44
}
45
- require .Equal (t , testCase .expectedResult , kitip . FromReq (req ))
45
+ require .Equal (t , testCase .expectedResult , httputil . GetRequestIP (req ))
46
46
})
47
47
}
48
48
}
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments