preserve ipv6 brackets and zone when stripping default ports

This commit is contained in:
Jay
2026-08-11 14:49:23 -04:00
parent 6586671c68
commit 54ac311051
2 changed files with 35 additions and 3 deletions
+2 -3
View File
@@ -30,13 +30,12 @@ func NormalizeURL(input string) (string, error) {
// lowercase host // lowercase host
parsed.Host = strings.ToLower(parsed.Host) parsed.Host = strings.ToLower(parsed.Host)
host := parsed.Hostname()
port := parsed.Port() port := parsed.Port()
// strip default ports // strip default ports by suffix-trim so ipv6 brackets and zone survive
if (parsed.Scheme == "wss" && port == "443") || if (parsed.Scheme == "wss" && port == "443") ||
(parsed.Scheme == "ws" && port == "80") { (parsed.Scheme == "ws" && port == "80") {
parsed.Host = host parsed.Host = strings.TrimSuffix(parsed.Host, ":"+port)
} }
parsed.Path = strings.TrimRight(parsed.Path, "/") parsed.Path = strings.TrimRight(parsed.Path, "/")
+33
View File
@@ -132,6 +132,21 @@ func TestNormalizeURL(t *testing.T) {
input: "ws://relay.example.com:80", input: "ws://relay.example.com:80",
expected: "ws://relay.example.com", expected: "ws://relay.example.com",
}, },
{
name: "strip default wss port preserves ipv6 brackets",
input: "wss://[::1]:443",
expected: "wss://[::1]",
},
{
name: "strip default ws port preserves ipv6 brackets",
input: "ws://[::1]:80",
expected: "ws://[::1]",
},
{
name: "strip default port preserves ipv6 zone",
input: "wss://[fe80::1%25eth0]:443/",
expected: "wss://[fe80::1%25eth0]",
},
{ {
name: "preserve non-default port", name: "preserve non-default port",
input: "wss://relay.example.com:8080", input: "wss://relay.example.com:8080",
@@ -174,6 +189,24 @@ func TestNormalizeURL(t *testing.T) {
} }
} }
func TestNormalizeURLIdempotent(t *testing.T) {
inputs := []string{
"wss://[::1]:443",
"ws://[::1]:80",
"wss://[fe80::1%25eth0]:443/",
"wss://relay.example.com:443/",
"wss://relay.example.com:8080/path",
}
for _, input := range inputs {
once, err := NormalizeURL(input)
assert.NoError(t, err)
twice, err := NormalizeURL(once)
assert.NoError(t, err)
assert.Equal(t, once, twice, "normalizing %q twice must be stable", input)
}
}
func TestNormalizeURLError(t *testing.T) { func TestNormalizeURLError(t *testing.T) {
_, err := NormalizeURL("http://relay.example.com") _, err := NormalizeURL("http://relay.example.com")
assert.ErrorIs(t, err, InvalidProtocol) assert.ErrorIs(t, err, InvalidProtocol)