add url validator

This commit is contained in:
Aneurin Barker Snook
2023-11-26 12:00:15 +00:00
parent 7160519ec3
commit a31f5d500a
2 changed files with 48 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
package validate
import "net/url"
// Validation error.
var (
ErrInvalidURL Error = NewError("invalid URL")
)
// URL validates a URL.
func URL(value string) error {
if _, err := url.ParseRequestURI(value); err != nil {
return ErrInvalidURL
}
return nil
}
+31
View File
@@ -0,0 +1,31 @@
package validate
import (
"errors"
"testing"
)
func TestURL(t *testing.T) {
type TestCase struct {
Input string
Err error
}
testCases := []TestCase{
{Input: "http://example.com"},
{Input: "http://subdomain.example.com"},
{Input: "http://www.example.com/some-page.html"},
{Input: "subdomain.com", Err: ErrInvalidURL},
{Input: "not a url", Err: ErrInvalidURL},
}
for n, tc := range testCases {
t.Logf("(%d) Testing %q", n, tc.Input)
err := URL(tc.Input)
if !errors.Is(err, tc.Err) {
t.Errorf("Expected error %v, got %v", tc.Err, err)
}
}
}