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

support ip chain without spaces in xForwarded header #684

Merged
merged 1 commit into from Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
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