From c312e11f6e57c9000c6c999f4ac96a58aa590196 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Mon, 21 Sep 2020 12:32:19 +0300 Subject: [PATCH] [#33] network: Add network endpoint getter to Address Signed-off-by: Leonard Lyubich --- pkg/network/address.go | 12 ++++++++++++ pkg/network/address_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 pkg/network/address_test.go diff --git a/pkg/network/address.go b/pkg/network/address.go index 465a26aba..e581578ce 100644 --- a/pkg/network/address.go +++ b/pkg/network/address.go @@ -2,6 +2,8 @@ package network import ( "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr-net" + "github.com/pkg/errors" ) // Address represents the NeoFS node @@ -14,6 +16,16 @@ func (a Address) String() string { return a.ma.String() } +// NetAddr returns network endpoint address in string format. +func (a Address) NetAddr() string { + ip, err := manet.ToNetAddr(a.ma) + if err != nil { + panic(errors.Wrap(err, "could not get net addr")) + } + + return ip.String() +} + // AddressFromString restores address from a string representation. func AddressFromString(s string) (*Address, error) { ma, err := multiaddr.NewMultiaddr(s) diff --git a/pkg/network/address_test.go b/pkg/network/address_test.go new file mode 100644 index 000000000..e53b7bfb5 --- /dev/null +++ b/pkg/network/address_test.go @@ -0,0 +1,28 @@ +package network + +import ( + "strings" + "testing" + + "github.com/multiformats/go-multiaddr" + "github.com/stretchr/testify/require" +) + +func TestAddress_NetAddr(t *testing.T) { + ip := "127.0.0.1" + port := "8080" + + ma, err := multiaddr.NewMultiaddr(strings.Join([]string{ + "/ip4", + ip, + "tcp", + port, + }, "/")) + + require.NoError(t, err) + + addr, err := AddressFromString(ma.String()) + require.NoError(t, err) + + require.Equal(t, ip+":"+port, addr.NetAddr()) +}