🏷️ Added custom JSON (un)marshler for Email domain

This commit is contained in:
Maxim Lebedev 2022-02-18 00:10:41 +05:00
parent f5888c3056
commit 6d5e90b852
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 23 additions and 0 deletions

View File

@ -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()