-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathemail.go
More file actions
43 lines (34 loc) · 861 Bytes
/
email.go
File metadata and controls
43 lines (34 loc) · 861 Bytes
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
package types
import (
"encoding/json"
"errors"
"net/mail"
)
// ErrValidationEmail is the sentinel error returned when an email fails validation
var ErrValidationEmail = errors.New("email: failed to pass regex validation")
// Email represents an email address.
// It is a string type that must pass regex validation before being marshalled
// to JSON or unmarshalled from JSON.
type Email string
func (e Email) MarshalJSON() ([]byte, error) {
m, err := mail.ParseAddress(string(e))
if err != nil {
return nil, ErrValidationEmail
}
return json.Marshal(m.Address)
}
func (e *Email) UnmarshalJSON(data []byte) error {
if e == nil {
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
m, err := mail.ParseAddress(s)
if err != nil {
return ErrValidationEmail
}
*e = Email(m.Address)
return nil
}