hostmaybeport.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package missinggo
  2. import (
  3. "net"
  4. "strconv"
  5. "strings"
  6. )
  7. // Represents a split host port.
  8. type HostMaybePort struct {
  9. Host string // Just the host, with no port.
  10. Port int // The port if NoPort is false.
  11. NoPort bool // Whether a port is specified.
  12. Err error // The error returned from net.SplitHostPort.
  13. }
  14. func (me *HostMaybePort) String() string {
  15. if me.NoPort {
  16. return me.Host
  17. }
  18. return net.JoinHostPort(me.Host, strconv.FormatInt(int64(me.Port), 10))
  19. }
  20. // Parse a "hostport" string, a concept that floats around the stdlib a lot
  21. // and is painful to work with. If no port is present, what's usually present
  22. // is just the host.
  23. func SplitHostMaybePort(hostport string) HostMaybePort {
  24. host, portStr, err := net.SplitHostPort(hostport)
  25. if err != nil {
  26. if strings.Contains(err.Error(), "missing port") {
  27. return HostMaybePort{
  28. Host: hostport,
  29. NoPort: true,
  30. }
  31. }
  32. return HostMaybePort{
  33. Err: err,
  34. }
  35. }
  36. portI64, err := strconv.ParseInt(portStr, 0, 0)
  37. if err != nil {
  38. return HostMaybePort{
  39. Host: host,
  40. Port: -1,
  41. Err: err,
  42. }
  43. }
  44. return HostMaybePort{
  45. Host: host,
  46. Port: int(portI64),
  47. }
  48. }