util.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package guerrilla
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "github.com/flashmob/go-guerrilla/mail"
  7. "github.com/flashmob/go-guerrilla/response"
  8. )
  9. var extractEmailRegex, _ = regexp.Compile(`<(.+?)@(.+?)>`) // go home regex, you're drunk!
  10. func extractEmail(str string) (mail.Address, error) {
  11. email := mail.Address{}
  12. var err error
  13. if len(str) > RFC2821LimitPath {
  14. return email, errors.New(response.Canned.FailPathTooLong.String())
  15. }
  16. if matched := extractEmailRegex.FindStringSubmatch(str); len(matched) > 2 {
  17. email.User = matched[1]
  18. email.Host = validHost(matched[2])
  19. } else if res := strings.Split(str, "@"); len(res) > 1 {
  20. email.User = strings.TrimSpace(res[0])
  21. email.Host = validHost(res[1])
  22. }
  23. err = nil
  24. if email.User == "" || email.Host == "" {
  25. err = errors.New(response.Canned.FailInvalidAddress.String())
  26. } else if len(email.User) > RFC2832LimitLocalPart {
  27. err = errors.New(response.Canned.FailLocalPartTooLong.String())
  28. } else if len(email.Host) > RFC2821LimitDomain {
  29. err = errors.New(response.Canned.FailDomainTooLong.String())
  30. }
  31. return email, err
  32. }
  33. var validhostRegex, _ = regexp.Compile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
  34. func validHost(host string) string {
  35. host = strings.Trim(host, " ")
  36. if validhostRegex.MatchString(host) {
  37. return host
  38. }
  39. return ""
  40. }