-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail_validator.go
56 lines (44 loc) · 1.07 KB
/
email_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
// Copyright 2021 Hyperscale. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package validator
import (
"context"
"fmt"
"net"
"net/mail"
"reflect"
"strings"
"time"
)
type emailValidator struct {
timeout time.Duration
}
// NewEmailValidator constructor.
func NewEmailValidator(opts ...EmailOption) Validator {
v := &emailValidator{
timeout: 100 * time.Millisecond,
}
for _, opt := range opts {
opt(v)
}
return v
}
func (v emailValidator) Validate(input interface{}) error {
switch email := input.(type) {
case string:
addr, err := mail.ParseAddress(email)
if err != nil {
return fmt.Errorf("parse address: %w", err)
}
parts := strings.Split(addr.Address, "@")
ctx, cancel := context.WithTimeout(context.Background(), v.timeout)
defer cancel()
if _, err := net.DefaultResolver.LookupMX(ctx, parts[1]); err != nil {
return fmt.Errorf("lookup mx: %w", err)
}
default:
return fmt.Errorf("invalid input type \"%v\" for email validator", reflect.TypeOf(email))
}
return nil
}