Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get client IP when using Cloudflare #2723

Merged
merged 3 commits into from May 28, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion context.go
Expand Up @@ -731,10 +731,15 @@ func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (e
// If the headers are nots syntactically valid OR the remote IP does not correspong to a trusted proxy,
// the remote IP (coming form Request.RemoteAddr) is returned.
func (c *Context) ClientIP() string {
if c.engine.AppEngine {
switch {
case c.engine.AppEngine:
if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
return addr
}
case c.engine.CloudflareProxy:
if addr := c.requestHeader("CF-Connecting-IP"); addr != "" {
return addr
}
}

remoteIP, trusted := c.RemoteIP()
Expand Down
8 changes: 8 additions & 0 deletions context_test.go
Expand Up @@ -1490,6 +1490,13 @@ func TestContextClientIP(t *testing.T) {
c.Request.Header.Del("X-Appengine-Remote-Addr")
assert.Equal(t, "40.40.40.40", c.ClientIP())

c.engine.AppEngine = false
c.engine.CloudflareProxy = true
assert.Equal(t, "60.60.60.60", c.ClientIP())

c.Request.Header.Del("CF-Connecting-IP")
assert.Equal(t, "40.40.40.40", c.ClientIP())

// no port
c.Request.RemoteAddr = "50.50.50.50"
assert.Empty(t, c.ClientIP())
Expand All @@ -1499,6 +1506,7 @@ func resetContextForClientIPTests(c *Context) {
c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
c.Request.Header.Set("CF-Connecting-IP", "60.60.60.60")
c.Request.RemoteAddr = " 40.40.40.40:42123 "
c.engine.AppEngine = false
}
Expand Down
4 changes: 4 additions & 0 deletions gin.go
Expand Up @@ -105,6 +105,10 @@ type Engine struct {
// 'X-AppEngine...' for better integration with that PaaS.
AppEngine bool

// If enabled, it will trust the CF-Connecting-IP header to determine the
// IP of the client.
CloudflareProxy bool

// If enabled, the url.RawPath will be used to find parameters.
UseRawPath bool

Expand Down