Add validation package #19

Merged
xbazzi merged 5 commits from issue-7 into master 2025-02-13 22:10:24 -07:00
2 changed files with 46 additions and 1 deletions
Showing only changes of commit e5aa8fe187 - Show all commits

View File

@ -2,6 +2,8 @@ package validation
import (
"errors"
"fmt"
"log"
neturl "net/url"
"strings"
)
@ -16,9 +18,16 @@ var (
// Music hosts that we support
Review

www.youtube.com

`www.youtube.com`
var musicHosts = []string{
"youtube.com",
"www.youtube.com",
}
func IsUrl(url string) (bool, *neturl.URL) {
// If a URL has no scheme, this will fail.
// So we'll add one if not present
if !strings.Contains(url, "://") {
url = fmt.Sprintf("https://%s", url)
}
parsed, err := neturl.ParseRequestURI(url)
return (err == nil), parsed
@ -37,6 +46,7 @@ func IsMusicUrl(url string) (bool, error) {
}
for _, host := range musicHosts {
log.Println(parsed.Host)
if host == parsed.Host {
return true, nil
}

View File

@ -1,6 +1,9 @@
package validation
import "testing"
import (
"log"
"testing"
)
func TestIsUrl(t *testing.T) {
is, _ := IsUrl("definitely not a url")
@ -16,6 +19,38 @@ func TestIsUrl(t *testing.T) {
}
}
func TestSchemeHandling(t *testing.T) {
// No scheme but valid url
is, _ := IsUrl("youtube.com")
if !is {
t.Error("URL without scheme came back as not a url")
}
// Preserve scheme
is, parsed := IsUrl("ftp://youtube.com")
if !is {
t.Error("URL without scheme came back as not a url")
}
if parsed.Scheme != "ftp" {
t.Error("URL scheme was replaced incorrectly")
}
}
func TestSupportedMusicUrls(t *testing.T) {
// Test actual music url
for _, url := range musicHosts {
log.Println(url)
is, _ := IsMusicUrl(url)
if !is {
t.Error("Supported service was detected as unsupported")
}
}
}
func TestIsMusicUrlErrors(t *testing.T) {
// Not a URL
is, err := IsMusicUrl("not a url")