host.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package http
  2. import (
  3. "fmt"
  4. "net"
  5. "strconv"
  6. "strings"
  7. )
  8. // ValidateEndpointHost validates that the host string passed in is a valid RFC
  9. // 3986 host. Returns error if the host is not valid.
  10. func ValidateEndpointHost(host string) error {
  11. var errors strings.Builder
  12. var hostname string
  13. var port string
  14. var err error
  15. if strings.Contains(host, ":") {
  16. hostname, port, err = net.SplitHostPort(host)
  17. if err != nil {
  18. errors.WriteString(fmt.Sprintf("\n endpoint %v, failed to parse, got ", host))
  19. errors.WriteString(err.Error())
  20. }
  21. if !ValidPortNumber(port) {
  22. errors.WriteString(fmt.Sprintf("port number should be in range [0-65535], got %v", port))
  23. }
  24. } else {
  25. hostname = host
  26. }
  27. labels := strings.Split(hostname, ".")
  28. for i, label := range labels {
  29. if i == len(labels)-1 && len(label) == 0 {
  30. // Allow trailing dot for FQDN hosts.
  31. continue
  32. }
  33. if !ValidHostLabel(label) {
  34. errors.WriteString("\nendpoint host domain labels must match \"[a-zA-Z0-9-]{1,63}\", but found: ")
  35. errors.WriteString(label)
  36. }
  37. }
  38. if len(hostname) == 0 && len(port) != 0 {
  39. errors.WriteString("\nendpoint host with port must not be empty")
  40. }
  41. if len(hostname) > 255 {
  42. errors.WriteString(fmt.Sprintf("\nendpoint host must be less than 255 characters, but was %d", len(hostname)))
  43. }
  44. if len(errors.String()) > 0 {
  45. return fmt.Errorf("invalid endpoint host%s", errors.String())
  46. }
  47. return nil
  48. }
  49. // ValidPortNumber returns whether the port is valid RFC 3986 port.
  50. func ValidPortNumber(port string) bool {
  51. i, err := strconv.Atoi(port)
  52. if err != nil {
  53. return false
  54. }
  55. if i < 0 || i > 65535 {
  56. return false
  57. }
  58. return true
  59. }
  60. // ValidHostLabel returns whether the label is a valid RFC 3986 host label.
  61. func ValidHostLabel(label string) bool {
  62. if l := len(label); l == 0 || l > 63 {
  63. return false
  64. }
  65. for _, r := range label {
  66. switch {
  67. case r >= '0' && r <= '9':
  68. case r >= 'A' && r <= 'Z':
  69. case r >= 'a' && r <= 'z':
  70. case r == '-':
  71. default:
  72. return false
  73. }
  74. }
  75. return true
  76. }