diff --git a/internal/domain/email.go b/internal/domain/email.go index caad714..d41c535 100644 --- a/internal/domain/email.go +++ b/internal/domain/email.go @@ -1,6 +1,8 @@ package domain import ( + "fmt" + "strconv" "strings" "testing" ) @@ -37,6 +39,27 @@ func ParseEmail(src string) (*Email, error) { return result, nil } +// UnmarshalJSON implements custom unmarshler for JSON. +func (e *Email) UnmarshalJSON(v []byte) error { + src, err := strconv.Unquote(string(v)) + if err != nil { + return fmt.Errorf("Email: UnmarshalJSON: %w", err) + } + + email, err := ParseEmail(src) + if err != nil { + return fmt.Errorf("Email: UnmarshalJSON: %w", err) + } + + *e = *email + + return nil +} + +func (e Email) MarshalJSON() ([]byte, error) { + return []byte(strconv.Quote(e.String())), nil +} + // TestEmail returns valid random generated email identifier. func TestEmail(tb testing.TB) *Email { tb.Helper()