-
Notifications
You must be signed in to change notification settings - Fork 163
/
suggestion.go
85 lines (67 loc) · 2.12 KB
/
suggestion.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
package emailverifier
import (
"strings"
"github.com/hbollon/go-edlib"
)
// SuggestDomain checks if domain has a typo and suggests a similar correct domain from metadata,
// returns a suggestion
func (v *Verifier) SuggestDomain(domain string) string {
if domain == "" {
return ""
}
domain = strings.ToLower(domain)
sld, tld := splitDomain(domain)
// If the domain is a valid second level domain and top level domain, do not suggest anything
if sld != "" && tld != "" {
if suggestionSecondLevelDomains[sld] && suggestionTopLevelDomains[tld] {
return ""
}
}
closestDomain := findClosestDomain(domain, freeDomains, domainThreshold)
if closestDomain != "" {
if closestDomain == domain {
// The domain exactly matches one of the suggestion domains, no suggestion provided.
return ""
}
// The domain closely matches one of the suggestion domains
return closestDomain
}
var localTypo bool
closestDomain = domain
closestSecondLevelDomain := findClosestDomain(sld, suggestionSecondLevelDomains, secondLevelThreshold)
closestTopLevelDomain := findClosestDomain(tld, suggestionTopLevelDomains, topLevelThreshold)
if closestSecondLevelDomain != "" && closestSecondLevelDomain != sld {
localTypo = true
closestDomain = strings.Replace(closestDomain, sld, closestSecondLevelDomain, -1)
}
if closestTopLevelDomain != "" && closestTopLevelDomain != tld && sld != "" {
localTypo = true
closestDomain = strings.Replace(closestDomain, tld, closestTopLevelDomain, -1)
}
if localTypo {
return closestDomain
}
return ""
}
// findClosestDomain finds the string most similar to the domain via Levenshtein algorithms.
func findClosestDomain(domain string, domains map[string]bool, threshold float32) string {
var maxDist = float32(-1)
var closestDomain string
if domain == "" || len(domains) == 0 {
return closestDomain
}
for d := range domains {
if domain == d {
return domain
}
dist, _ := edlib.StringsSimilarity(domain, d, edlib.Levenshtein)
if dist > maxDist {
maxDist = dist
closestDomain = d
}
}
if maxDist >= threshold && closestDomain != "" {
return closestDomain
}
return ""
}