-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
96 lines (84 loc) · 1.69 KB
/
utils.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"errors"
"fmt"
"math/rand"
"net"
"os"
"regexp"
"strings"
)
const (
domainRe = "[-a-z0-9]+(?:[.][-a-z0-9]+)+"
emailRe = "(?:[-A-Za-z0-9!#$%&'*+/=?^_`{|}~.]+|\"(?:\\.|[^\\\"])*\")@[-A-Za-z0-9]+(?:[.][-A-Za-z0-9]+)+"
listnameRe = "[a-z0-9][-a-z0-9.+_]*"
)
func addrToIP(hostport string) (net.IP, error) {
h, _, err := net.SplitHostPort(hostport)
if err != nil {
return nil, err
}
ip := net.ParseIP(h)
if ip == nil {
return nil, errors.New("Illegal syntax")
}
return ip, nil
}
func addressLiteral(ip net.IP) string {
if ip4 := ip.To4(); ip4 != nil {
return fmt.Sprintf("[%s]", ip4)
} else {
return fmt.Sprintf("[IPv6:%s]", ip.String())
}
}
func canonicDomain(d string) string {
return toLowerASCII(d)
}
func canonicEmail(e string) string {
return toLowerASCII(strings.TrimSpace(e))
}
func isDir(p string) bool {
fi, err := os.Stat(p)
if err != nil {
return false
}
return fi.IsDir()
}
func toLowerASCII(s string) string {
return strings.Map(
func(r rune) rune {
if 'A' <= r && r <= 'Z' {
return r + ('a' - 'A')
}
return r
}, s,
)
}
func uniqueId() string {
// Not exceeding 32 bit signed int; 0 and 1 do not appear.
return fmt.Sprintf("%010d", rand.Intn(int(^uint32(2)>>1))+2)
}
func validateDomain(d string) error {
d = canonicDomain(d)
matched, err := regexp.Match("^"+domainRe+"$", []byte(d))
if err != nil {
panic(err)
}
if matched {
return nil
}
return errors.New("invalid domain name")
}
func validateEmail(e string) error {
if e == "" {
return nil
}
matched, err := regexp.Match("^"+emailRe+"$", []byte(e))
if err != nil {
panic(err)
}
if matched {
return nil
}
return errors.New("invalid email address")
}