fix: do not alter the original URL if there is no tracker parameter

This commit is contained in:
Frédéric Guillot 2024-07-25 21:47:03 -07:00
parent 92f3dc26e4
commit 37309adbc0
2 changed files with 28 additions and 9 deletions

View File

@ -78,14 +78,21 @@ func RemoveTrackingParameters(inputURL string) (string, error) {
}
queryParams := parsedURL.Query()
hasTrackers := false
// Remove tracking parameters
for param := range queryParams {
if trackingParams[strings.ToLower(param)] {
queryParams.Del(param)
hasTrackers = true
}
}
// Do not modify the URL if there are no tracking parameters
if !hasTrackers {
return inputURL, nil
}
parsedURL.RawQuery = queryParams.Encode()
// Remove trailing "?" if query string is empty

View File

@ -11,9 +11,10 @@ import (
func TestRemoveTrackingParams(t *testing.T) {
tests := []struct {
name string
input string
expected string
name string
input string
expected string
strictComparison bool
}{
{
name: "URL with tracking parameters",
@ -31,9 +32,10 @@ func TestRemoveTrackingParams(t *testing.T) {
expected: "https://example.com/page?id=123&foo=bar",
},
{
name: "URL with no parameters",
input: "https://example.com/page",
expected: "https://example.com/page",
name: "URL with no parameters",
input: "https://example.com/page",
expected: "https://example.com/page",
strictComparison: true,
},
{
name: "URL with mixed case tracking parameters",
@ -60,15 +62,22 @@ func TestRemoveTrackingParams(t *testing.T) {
input: "https://example.com/page?name=John%20Doe&utm_source=newsletter",
expected: "https://example.com/page?name=John+Doe",
},
{
name: "Non-standard URL parameter with no tracker",
input: "https://example.com/foo.jpg?crop/1420x708/format/webp",
expected: "https://example.com/foo.jpg?crop/1420x708/format/webp",
strictComparison: true,
},
{
name: "Invalid URL",
input: "https://example|org/",
expected: "",
},
{
name: "Non-HTTP URL",
input: "mailto:user@example.org",
expected: "mailto:user@example.org",
name: "Non-HTTP URL",
input: "mailto:user@example.org",
expected: "mailto:user@example.org",
strictComparison: true,
},
}
@ -83,6 +92,9 @@ func TestRemoveTrackingParams(t *testing.T) {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if tt.strictComparison && result != tt.expected {
t.Errorf("removeTrackingParams(%q) = %q, want %q", tt.input, result, tt.expected)
}
if !urlsEqual(result, tt.expected) {
t.Errorf("removeTrackingParams(%q) = %q, want %q", tt.input, result, tt.expected)
}