From 95f5ef6ff56c8c6be315a52f567a987e28df1730 Mon Sep 17 00:00:00 2001 From: sunshineplan Date: Sun, 28 Nov 2021 11:11:31 +0800 Subject: [PATCH] Treat RemoteAddr "@" as 127.0.0.1 --- context.go | 4 ++++ context_test.go | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/context.go b/context.go index a97dd409..5e538aec 100644 --- a/context.go +++ b/context.go @@ -785,10 +785,14 @@ func (e *Engine) isTrustedProxy(ip net.IP) bool { } // RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). +// If Request.RemoteAddr is @ which may be proxy pass by a unix listener, treat it as 127.0.0.1. // It also checks if the remoteIP is a trusted proxy or not. // In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks // defined by Engine.SetTrustedProxies() func (c *Context) RemoteIP() (net.IP, bool) { + if c.Request.RemoteAddr == "@" { + c.Request.RemoteAddr = "127.0.0.1:" + } ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) if err != nil { return nil, false diff --git a/context_test.go b/context_test.go index c286c0f4..363fd80f 100644 --- a/context_test.go +++ b/context_test.go @@ -1401,6 +1401,12 @@ func TestContextClientIP(t *testing.T) { c.Request.RemoteAddr = "50.50.50.50" assert.Empty(t, c.ClientIP()) + // @ + c.Request.RemoteAddr = "@" + assert.Equal(t, "127.0.0.1", c.ClientIP()) + c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ") + assert.Equal(t, "30.30.30.30", c.ClientIP()) + // Tests exercising the TrustedProxies functionality resetContextForClientIPTests(c)