[#33] network: Add network endpoint getter to Address

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-09-21 12:32:19 +03:00 committed by Alex Vanin
parent 73ee5105ff
commit c312e11f6e
2 changed files with 40 additions and 0 deletions

View file

@ -2,6 +2,8 @@ package network
import ( import (
"github.com/multiformats/go-multiaddr" "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
"github.com/pkg/errors"
) )
// Address represents the NeoFS node // Address represents the NeoFS node
@ -14,6 +16,16 @@ func (a Address) String() string {
return a.ma.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. // AddressFromString restores address from a string representation.
func AddressFromString(s string) (*Address, error) { func AddressFromString(s string) (*Address, error) {
ma, err := multiaddr.NewMultiaddr(s) ma, err := multiaddr.NewMultiaddr(s)

View file

@ -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())
}