1
0
mirror of https://github.com/taigrr/shorturl synced 2025-01-18 04:03:16 -08:00

Validate URL before shorten

This commit is contained in:
srxr 2021-03-27 07:03:43 +00:00
parent 36983ae9f7
commit a55db041cc
No known key found for this signature in database
GPG Key ID: 5F5DB27AF89FA243
2 changed files with 23 additions and 1 deletions

View File

@ -1,6 +1,9 @@
package main
import (
"fmt"
nurl "net/url"
"strings"
"time"
)
@ -25,11 +28,27 @@ func GenerateID() string {
}
func NewURL(target string) (url *URL, err error) {
url = &URL{ID: GenerateID(), URL: target, CreatedAt: time.Now()}
u, err := parse(target)
if err != nil {
return nil, err
}
url = &URL{ID: GenerateID(), URL: u.String(), CreatedAt: time.Now()}
err = db.Save(url)
return
}
func parse(target string) (u *nurl.URL, err error) {
u, err = nurl.Parse(strings.TrimSpace(target))
if err != nil {
return nil, fmt.Errorf("URL (%s) no satisfied", target)
}
if u.Scheme == "" || u.Host == "" {
return nil, fmt.Errorf("URL (%s) without scheme or host", target)
}
return u, nil
}
// SetName ...
func (u *URL) SetName(name string) error {
u.Name = name

View File

@ -48,4 +48,7 @@ func TestNewURL(t *testing.T) {
assert.NotEqual(u.ID, "")
assert.Equal(u.URL, "https://www.google.com")
assert.Equal(u.Name, "")
u, err = NewURL("www.google.com")
assert.NotNil(t, err)
}