/
validator.go
67 lines (54 loc) · 1.64 KB
/
validator.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
56
57
58
59
60
61
62
63
64
65
66
67
package validate
import (
"fmt"
"net/url"
"regexp"
"github.com/pkg/errors"
)
// Validator describes a a validator for a user service.
type Validator interface {
// Normalize the service user name.
// For example, on Twitter, "@username" becomes "username" or "Gabriel"
// becomes "gabriel".
NormalizeName(name string) string
// ValidateName validates the service user name.
ValidateName(name string) error
// NormalizeURL normalizes an url string.
NormalizeURL(name string, urs string) (string, error)
// ValidateURL validates the URL string.
ValidateURL(name string, urs string) error
}
var services = map[string]Validator{
"twitter": Twitter,
"github": Github,
"reddit": Reddit,
"https": HTTPS,
"echo": Echo,
}
// Lookup service by name.
func Lookup(service string) (Validator, error) {
out, ok := services[service]
if out == nil || !ok {
return nil, errors.Errorf("service not found: %s", service)
}
return out, nil
}
var regAlphaNumericWithDash = regexp.MustCompile(`^[a-z0-9-]+$`)
var regAlphaNumericWithUnderscore = regexp.MustCompile(`^[a-z0-9_]+$`)
var regAlphaNumericWithDashUnderscore = regexp.MustCompile(`^[a-z0-9-_]+$`)
func isAlphaNumericWithDash(s string) bool {
return regAlphaNumericWithDash.MatchString(s)
}
func isAlphaNumericWithUnderscore(s string) bool {
return regAlphaNumericWithUnderscore.MatchString(s)
}
func isAlphaNumericWithDashUnderscore(s string) bool {
return regAlphaNumericWithDashUnderscore.MatchString(s)
}
func basicURLString(urs string) (string, error) {
ur, err := url.Parse(urs)
if err != nil {
return "", err
}
return fmt.Sprintf("%s://%s%s", ur.Scheme, ur.Host, ur.Path), nil
}