diff --git a/nameresolution/consul/consul.go b/nameresolution/consul/consul.go index a92630591b..66533b4c30 100644 --- a/nameresolution/consul/consul.go +++ b/nameresolution/consul/consul.go @@ -323,7 +323,13 @@ func formatAddress(address string, port string) (addr string, err error) { return fmt.Sprintf("[%s]:%s", address, port), nil } - return "", fmt.Errorf("invalid ip address %s", address) + // addr is not a valid IP address + // use net.JoinHostPort to format address if address is a valid hostname + if _, err := net.LookupHost(address); err == nil { + return net.JoinHostPort(address, port), nil + } + + return "", fmt.Errorf("invalid ip address or unreachable hostname: %s", address) } // getConfig configuration from metadata, defaults are best suited for self-hosted mode. diff --git a/nameresolution/consul/consul_test.go b/nameresolution/consul/consul_test.go index 8f269ffde3..3f36c3394b 100644 --- a/nameresolution/consul/consul_test.go +++ b/nameresolution/consul/consul_test.go @@ -845,6 +845,35 @@ func TestResolveID(t *testing.T) { assert.Equal(t, "[2001:db8:3333:4444:5555:6666:7777:8888]:50005", addr) }, }, + { + "should get localhost (hostname) from service", + nr.ResolveRequest{ + ID: "test-app", + }, + func(t *testing.T, req nr.ResolveRequest) { + t.Helper() + mock := mockClient{ + mockHealth: mockHealth{ + serviceResult: []*consul.ServiceEntry{ + { + Service: &consul.AgentService{ + Address: "localhost", + Port: 8600, + Meta: map[string]string{ + "DAPR_PORT": "50005", + }, + }, + }, + }, + }, + } + resolver := newResolver(logger.NewLogger("test"), testConfig, &mock, ®istry{}, make(chan struct{})) + + addr, _ := resolver.ResolveID(context.Background(), req) + + assert.Equal(t, "localhost:50005", addr) + }, + }, { "should get random address from service", nr.ResolveRequest{