github.com/mattyr/nomad@v0.3.3-0.20160919021406-3485a065154a/client/rpcproxy/server_endpoint.go (about) 1 package rpcproxy 2 3 import ( 4 "fmt" 5 "net" 6 "strings" 7 ) 8 9 const ( 10 defaultNomadRPCPort = "4647" 11 ) 12 13 // EndpointKey is used in maps and for equality tests. A key is based on endpoints. 14 type EndpointKey struct { 15 name string 16 } 17 18 // Equal compares two EndpointKey objects 19 func (k *EndpointKey) Equal(x *EndpointKey) bool { 20 return k.name == x.name 21 } 22 23 // ServerEndpoint contains the address information for to connect to a Nomad 24 // server. 25 // 26 // TODO(sean@): Server is stubbed out so that in the future it can hold a 27 // reference to Node (and ultimately Node.ID). 28 type ServerEndpoint struct { 29 // Name is the unique lookup key for a Server instance 30 Name string 31 Host string 32 Port string 33 Addr net.Addr 34 } 35 36 // Key returns the corresponding Key 37 func (s *ServerEndpoint) Key() *EndpointKey { 38 return &EndpointKey{ 39 name: s.Name, 40 } 41 } 42 43 // NewServerEndpoint creates a new Server instance with a resolvable 44 // endpoint. `name` can be either an IP address or a DNS name. If `name` is 45 // a DNS name, it must be resolvable to an IP address (most inputs are IP 46 // addresses, not DNS names, but both work equally well when the name is 47 // resolvable). 48 func NewServerEndpoint(name string) (*ServerEndpoint, error) { 49 s := &ServerEndpoint{ 50 Name: name, 51 } 52 53 var host, port string 54 var err error 55 host, port, err = net.SplitHostPort(name) 56 if err == nil { 57 s.Host = host 58 s.Port = port 59 } else { 60 if strings.Contains(err.Error(), "missing port") { 61 s.Host = name 62 s.Port = defaultNomadRPCPort 63 } else { 64 return nil, err 65 } 66 } 67 68 if s.Addr, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(s.Host, s.Port)); err != nil { 69 return nil, err 70 } 71 72 return s, err 73 } 74 75 // String returns a string representation of Server 76 func (s *ServerEndpoint) String() string { 77 var addrStr, networkStr string 78 if s.Addr != nil { 79 addrStr = s.Addr.String() 80 networkStr = s.Addr.Network() 81 } 82 83 return fmt.Sprintf("%s (%s:%s)", s.Name, networkStr, addrStr) 84 }