-
Notifications
You must be signed in to change notification settings - Fork 8
/
urlvalidator.go
55 lines (48 loc) · 1.18 KB
/
urlvalidator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package urlutil
import (
"fmt"
"net/url"
"sort"
"strings"
)
type URLValidator struct {
RequiredSchemes map[string]int
}
func (uv *URLValidator) SchemesToLower() {
newSchemes := map[string]int{}
for scheme, v := range uv.RequiredSchemes {
newSchemes[strings.ToLower(scheme)] = v
}
uv.RequiredSchemes = newSchemes
}
func (uv *URLValidator) ValidateURLString(s string) (*url.URL, error) {
if len(strings.TrimSpace(s)) < 1 {
return nil, fmt.Errorf("URL is empty.")
}
u, err := url.ParseRequestURI(s)
if err != nil {
return u, err
}
return uv.ValidateURL(u)
}
func (uv *URLValidator) ValidateURL(u *url.URL) (*url.URL, error) {
if len(uv.RequiredSchemes) > 0 {
if _, ok := uv.RequiredSchemes[u.Scheme]; !ok {
return u,
fmt.Errorf("Scheme `%v` is not in list of required schemes: %v",
u.Scheme, uv.RequiredSchemesSortedString())
}
}
return u, nil
}
func (uv *URLValidator) RequiredSchemesSorted() []string {
schemes := []string{}
for scheme := range uv.RequiredSchemes {
schemes = append(schemes, scheme)
}
sort.Strings(schemes)
return schemes
}
func (uv *URLValidator) RequiredSchemesSortedString() string {
return strings.Join(uv.RequiredSchemesSorted(), ",")
}