Centralize link URL validation

This commit is contained in:
2026-06-02 18:38:16 +00:00
parent c4cfd3fc74
commit 42fb4aa82a
10 changed files with 166 additions and 46 deletions

26
internal/link/url.go Normal file
View File

@@ -0,0 +1,26 @@
package link
import (
"fmt"
"net/url"
)
func ValidateHTTPURL(value string) error {
parsed, err := url.Parse(value)
if err != nil {
return fmt.Errorf("must be a valid URL")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return fmt.Errorf("must use http or https")
}
if parsed.Host == "" {
return fmt.Errorf("must include a host")
}
if parsed.RawQuery != "" {
return fmt.Errorf("must not include a query string")
}
if parsed.Fragment != "" {
return fmt.Errorf("must not include a fragment")
}
return nil
}

39
internal/link/url_test.go Normal file
View File

@@ -0,0 +1,39 @@
package link
import (
"strings"
"testing"
)
func TestValidateHTTPURL(t *testing.T) {
tests := []struct {
name string
value string
wantErr string
}{
{name: "http", value: "http://reports.example.com/archive"},
{name: "https", value: "https://reports.example.com/archive"},
{name: "missing host", value: "https:///archive", wantErr: "must include a host"},
{name: "unsupported scheme", value: "ftp://reports.example.com/archive", wantErr: "must use http or https"},
{name: "query string", value: "https://reports.example.com/archive?preview=1", wantErr: "must not include a query string"},
{name: "fragment", value: "https://reports.example.com/archive#top", wantErr: "must not include a fragment"},
{name: "parse failure", value: "http://[::1", wantErr: "must be a valid URL"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateHTTPURL(tt.value)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("ValidateHTTPURL() error = %v", err)
}
return
}
if err == nil {
t.Fatal("ValidateHTTPURL() error = nil, want error")
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("ValidateHTTPURL() error = %q, want %q", err, tt.wantErr)
}
})
}
}