Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion controllers/ipservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func getPublicIP(w http.ResponseWriter, r *http.Request) {

func parseIP(r *http.Request) (string, error) {
// Get Public IP from header
ip := r.Header.Get("X-REAL-IP")
ip := strings.TrimSpace(r.Header.Get("X-REAL-IP"))
ipnet := net.ParseIP(ip)
if ipnet != nil && !ncutils.IpIsPrivate(ipnet) {
return ip, nil
Expand All @@ -53,6 +53,7 @@ func parseIP(r *http.Request) (string, error) {
forwardips := r.Header.Get("X-FORWARDED-FOR")
iplist := strings.Split(forwardips, ",")
for _, ip := range iplist {
ip = strings.TrimSpace(ip)
ipnet := net.ParseIP(ip)
if ipnet != nil && !ncutils.IpIsPrivate(ipnet) {
return ip, nil
Expand Down
21 changes: 21 additions & 0 deletions controllers/ipservice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package controller

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestParseIPTrimsForwardedForEntries(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
req.Header.Set("X-FORWARDED-FOR", "10.0.0.1, 8.8.8.8")
req.RemoteAddr = "10.0.0.2:1234"

ip, err := parseIP(req)
if err != nil {
t.Fatalf("parseIP() returned error: %v", err)
}
if ip != "8.8.8.8" {
t.Fatalf("parseIP() = %q, want %q", ip, "8.8.8.8")
}
}