-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.go
56 lines (47 loc) · 1.05 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
package validator
import (
"fmt"
"regexp"
"strings"
)
// V is a validator implementation
type V struct {
cfg *Config
}
var defaultLogfunc = func(msg string, args ...any) {
fmt.Printf(msg+"\n", args...)
}
// New validator
func New(cfg *Config) *V {
if cfg.Log == nil {
cfg.Log = defaultLogfunc
}
spamregexes, err := parseSpamlist(cfg.Email.Spamlist)
if err != nil {
cfg.Log("cannot parse spamlist: %v", err)
}
cfg.Email.spamlist = spamregexes
return &V{cfg}
}
func parseSpamlist(patterns []string) ([]*regexp.Regexp, error) {
regexes := []*regexp.Regexp{}
for _, pattern := range patterns {
rule, err := regexp.Compile("^" + parsePattern(pattern) + "$")
if err != nil {
return regexes, err
}
regexes = append(regexes, rule)
}
return regexes, nil
}
func parsePattern(pattern string) string {
var regexpattern strings.Builder
for _, runeItem := range pattern {
if runeItem == '*' {
regexpattern.WriteString("(.*)")
continue
}
regexpattern.WriteString(regexp.QuoteMeta(string(runeItem)))
}
return regexpattern.String()
}