auth/internal/domain/email.go

82 lines
1.6 KiB
Go
Raw Normal View History

2021-12-26 19:04:01 +00:00
package domain
2022-01-08 20:07:14 +00:00
import (
"fmt"
"strconv"
2022-01-08 20:07:14 +00:00
"strings"
"testing"
)
2022-01-29 17:50:45 +00:00
// Email represent email identifier.
2022-01-08 20:07:14 +00:00
type Email struct {
2022-01-30 17:49:25 +00:00
user string
host string
subAddress string
2022-01-08 20:07:14 +00:00
}
const DefaultEmailPartsLength int = 2
var ErrEmailInvalid error = NewError(ErrorCodeInvalidRequest, "cannot parse email", "")
2022-01-08 20:07:14 +00:00
2022-01-29 17:50:45 +00:00
// ParseEmail parse strings to email identifier.
2022-01-29 14:43:00 +00:00
func ParseEmail(src string) (*Email, error) {
2022-01-08 20:07:14 +00:00
parts := strings.Split(strings.TrimPrefix(src, "mailto:"), "@")
if len(parts) != DefaultEmailPartsLength {
2022-01-08 20:07:14 +00:00
return nil, ErrEmailInvalid
}
2022-01-30 17:49:25 +00:00
result := &Email{
user: parts[0],
host: parts[1],
subAddress: "",
}
if userParts := strings.SplitN(parts[0], `+`, DefaultEmailPartsLength); len(userParts) > 1 {
2022-01-30 17:49:25 +00:00
result.user = userParts[0]
result.subAddress = userParts[1]
}
return result, nil
2022-01-08 20:07:14 +00:00
}
// 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
}
2022-01-29 17:50:45 +00:00
// TestEmail returns valid random generated email identifier.
2022-01-08 20:07:14 +00:00
func TestEmail(tb testing.TB) *Email {
tb.Helper()
return &Email{
2022-01-30 17:49:25 +00:00
user: "user",
subAddress: "",
host: "example.com",
2022-01-08 20:07:14 +00:00
}
}
2022-01-29 17:50:45 +00:00
// String returns string representation of email identifier.
2022-01-08 20:07:14 +00:00
func (e Email) String() string {
2022-01-30 17:49:25 +00:00
if e.subAddress == "" {
return e.user + "@" + e.host
}
return e.user + "+" + e.subAddress + "@" + e.host
2022-01-08 20:07:14 +00:00
}