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:
parent
36983ae9f7
commit
a55db041cc
21
models.go
21
models.go
@ -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
|
||||
|
@ -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)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user