Skip to content

Instantly share code, notes, and snippets.

@bwaidelich bwaidelich/main.go
Last active Jan 31, 2019

Embed
What would you like to do?
Golang Value Object tests
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
You can’t perform that action at this time.