Last active
January 31, 2019 14:57
-
-
Save bwaidelich/1c51ef9b98b1b4cb16b3db875f3bcebc to your computer and use it in GitHub Desktop.
Golang Value Object tests
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
package main | |
import ( | |
"fmt" | |
"regexp" | |
) | |
// EmailAddress Value Object | |
type EmailAddress string | |
// Value Render the EmailAddress as simple string by default | |
func (e EmailAddress) Value() string { | |
return string(e) | |
} | |
// FromString Static "constructor" | |
func FromString(value string) (EmailAddress, error) { | |
var e EmailAddress | |
match, _ := regexp.MatchString(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`, value) | |
if !match { | |
return e, fmt.Errorf("%s is not a valid email address", value) | |
} | |
return EmailAddress(value), nil | |
} | |
// Host returns the host part of an email address | |
func (e EmailAddress) Host() string { | |
return regexp.MustCompile(`([a-z0-9._%+\-]+)@([a-z0-9.\-]+\.[a-z]{2,4})$`).FindStringSubmatch(string(e))[2] | |
} | |
func main() { | |
email, err := FromString("foo@bar.com") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(email.Host()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment