-
Notifications
You must be signed in to change notification settings - Fork 146
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add recipient struct with marshalling/unmarshalling
- Loading branch information
Showing
2 changed files
with
47 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package mailgun | ||
|
||
import "fmt" | ||
import "strings" | ||
|
||
type Recipient struct { | ||
Name string `json:"-"` | ||
Email string `json:"-"` | ||
} | ||
|
||
func (r Recipient) String() string { | ||
if r.Name != "" { | ||
return fmt.Sprintf("%s <%s>", r.Name, r.Email) | ||
} | ||
return r.Email | ||
} | ||
|
||
// MarshalText satisfies TextMarshaler | ||
func (r Recipient) MarshalText() ([]byte, error) { | ||
return []byte(r.String()), nil | ||
} | ||
|
||
// UnmarshalText satisfies TextUnmarshaler | ||
func (r *Recipient) UnmarshalText(text []byte) error { | ||
s := string(text) | ||
if s[len(s)-1:] != ">" { | ||
*r = Recipient{Email: s} | ||
return nil | ||
} | ||
|
||
i := strings.Index(s, "<") | ||
// at least 1 char followed by a space | ||
if i < 2 { | ||
return fmt.Errorf("malformed recipient string '%s'", s) | ||
} | ||
*r = Recipient{ | ||
Name: strings.TrimSpace(s[:i]), | ||
Email: s[i+1 : len(s)-1], | ||
} | ||
|
||
return nil | ||
} |