Skip to content

Commit

Permalink
support ip chain without spaces in xForwarded header (#684)
Browse files Browse the repository at this point in the history
Co-authored-by: evgenyKharitonov <evgeny.kharitonov@tailorbrands.com>
  • Loading branch information
evgenyKharitonov and evgenyKharitonov committed Dec 2, 2021
1 parent 0316d5a commit e4fe258
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
2 changes: 1 addition & 1 deletion middleware/realip.go
Expand Up @@ -46,7 +46,7 @@ func realIP(r *http.Request) string {
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ", ")
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
Expand Down
37 changes: 23 additions & 14 deletions middleware/realip_test.go
Expand Up @@ -33,26 +33,35 @@ func TestXRealIP(t *testing.T) {
}

func TestXForwardForIP(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add("X-Forwarded-For", "100.100.100.100")
w := httptest.NewRecorder()
xForwardedForIPs := []string{
"100.100.100.100",
"100.100.100.100, 200.200.200.200",
"100.100.100.100,200.200.200.200",
}

r := chi.NewRouter()
r.Use(RealIP)

realIP := ""
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
realIP = r.RemoteAddr
w.Write([]byte("Hello World"))
})
r.ServeHTTP(w, req)
for _, v := range xForwardedForIPs {
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add("X-Forwarded-For", v)

if w.Code != 200 {
t.Fatal("Response Code should be 200")
}
w := httptest.NewRecorder()

if realIP != "100.100.100.100" {
t.Fatal("Test get real IP error.")
realIP := ""
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
realIP = r.RemoteAddr
w.Write([]byte("Hello World"))
})
r.ServeHTTP(w, req)

if w.Code != 200 {
t.Fatal("Response Code should be 200")
}

if realIP != "100.100.100.100" {
t.Fatal("Test get real IP error.")
}
}
}

Expand Down

0 comments on commit e4fe258

Please sign in to comment.