ip_test.go

46 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
package router

import (
	"net/http"
	"testing"
)

func TestClientIP_RemoteAddr(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	r.RemoteAddr = "192.168.1.1:12345"

	if ip := ClientIP(r); ip != "192.168.1.1:12345" {
		t.Errorf("expected RemoteAddr, got %q", ip)
	}
}

func TestClientIP_XForwardedFor_Single(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("X-Forwarded-For", "10.0.0.1")

	if ip := ClientIP(r); ip != "10.0.0.1" {
		t.Errorf("expected 10.0.0.1, got %q", ip)
	}
}

func TestClientIP_XForwardedFor_Multiple(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("X-Forwarded-For", "10.0.0.1, 10.0.0.2, 10.0.0.3")

	if ip := ClientIP(r); ip != "10.0.0.1" {
		t.Errorf("expected first IP 10.0.0.1, got %q", ip)
	}
}

func TestStripPort(t *testing.T) {
	tests := []struct{ in, want string }{
		{"example.com:443", "example.com"},
		{"example.com", "example.com"},
		{"[::1]:8080", "::1"},
	}
	for _, tt := range tests {
		if got := stripPort(tt.in); got != tt.want {
			t.Errorf("stripPort(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}