Skip to content

Commit

Permalink
feat(httpx): use cf-connecting-ip header for client IP
Browse files Browse the repository at this point in the history
  • Loading branch information
mfzl committed Jun 14, 2024
1 parent 5219810 commit d831c7f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
2 changes: 2 additions & 0 deletions httpx/client_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ func GetClientIPAddressesWithoutInternalIPs(ipAddresses []string) (string, error
func ClientIP(r *http.Request) string {
if trueClientIP := r.Header.Get("True-Client-IP"); trueClientIP != "" {
return trueClientIP
} else if cfConnectingIP := r.Header.Get("Cf-Connecting-IP"); cfConnectingIP != "" {
return cfConnectingIP
} else if realClientIP := r.Header.Get("X-Real-IP"); realClientIP != "" {
return realClientIP
} else if forwardedIP := r.Header.Get("X-Forwarded-For"); forwardedIP != "" {
Expand Down
13 changes: 11 additions & 2 deletions httpx/client_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,35 @@ func TestClientIP(t *testing.T) {
Header: http.Header{},
}
req.Header.Add("true-client-ip", "1.0.0.1")
req.Header.Add("x-real-ip", "1.0.0.2")
req.Header.Add("cf-connecting-ip", "1.0.0.2")
req.Header.Add("x-real-ip", "1.0.0.3")
req.Header.Add("x-forwarded-for", "192.168.1.1,1.0.0.3,10.0.0.1")
t.Run("true-client-ip", func(t *testing.T) {
req := req.Clone(context.Background())
assert.Equal(t, "1.0.0.1", ClientIP(req))
})
t.Run("x-real-ip", func(t *testing.T) {
t.Run("cf-connecting-ip", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
assert.Equal(t, "1.0.0.2", ClientIP(req))
})
t.Run("x-real-ip", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
assert.Equal(t, "1.0.0.3", ClientIP(req))
})
t.Run("x-forwarded-for", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
req.Header.Del("x-real-ip")
assert.Equal(t, "1.0.0.3", ClientIP(req))
})
t.Run("remote-addr", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
req.Header.Del("x-real-ip")
req.Header.Del("x-forwarded-for")
assert.Equal(t, "1.0.0.4", ClientIP(req))
Expand Down

0 comments on commit d831c7f

Please sign in to comment.