Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Last active January 31, 2019 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwaidelich/1c51ef9b98b1b4cb16b3db875f3bcebc to your computer and use it in GitHub Desktop.
Save bwaidelich/1c51ef9b98b1b4cb16b3db875f3bcebc to your computer and use it in GitHub Desktop.
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