ACMEv2 client library for Go.

hostname.go 870B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package acmeutils
  2. import (
  3. "fmt"
  4. "golang.org/x/net/idna"
  5. "regexp"
  6. "strings"
  7. )
  8. var reHostname = regexp.MustCompilePOSIX(`^([a-z0-9_-]+\.)*[a-z0-9_-]+$`)
  9. // Normalizes the hostname given. If the hostname is not valid, returns "" and
  10. // an error.
  11. func NormalizeHostname(name string) (string, error) {
  12. isWildcard := strings.HasPrefix(name, "*.")
  13. if isWildcard {
  14. name = name[2:]
  15. }
  16. name = strings.TrimSuffix(strings.ToLower(name), ".")
  17. name, err := idna.ToASCII(name)
  18. if err != nil {
  19. return "", fmt.Errorf("IDN error: %#v: %v", name, err)
  20. }
  21. if !reHostname.MatchString(name) {
  22. return "", fmt.Errorf("invalid hostname: %#v", name)
  23. }
  24. if isWildcard {
  25. name = "*." + name
  26. }
  27. return name, nil
  28. }
  29. // Returns true iff the given string is a valid hostname.
  30. func ValidateHostname(name string) bool {
  31. _, err := NormalizeHostname(name)
  32. return err == nil
  33. }