Fix multiaddr json unmarshalling in NetAddrsListen

This commit is contained in:
Łukasz Magiera 2019-07-09 15:35:32 +02:00
parent 1bead4bb7e
commit 7069d57432
4 changed files with 32 additions and 6 deletions

View File

@ -4,7 +4,6 @@ import (
"context"
"github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// Version provides various build-time information
@ -37,7 +36,7 @@ type API interface {
NetPeers(context.Context) ([]peer.AddrInfo, error) // TODO: check serialization
NetConnect(context.Context, peer.AddrInfo) error
NetAddrsListen(context.Context) ([]ma.Multiaddr, error)
NetAddrsListen(context.Context) (MultiaddrSlice, error)
// // ping
// Struct

View File

@ -4,7 +4,6 @@ import (
"context"
"github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// Struct implements API passing calls to user-provided function values.
@ -15,7 +14,7 @@ type Struct struct {
NetPeers func(context.Context) ([]peer.AddrInfo, error)
NetConnect func(context.Context, peer.AddrInfo) error
NetAddrsListen func(context.Context) ([]ma.Multiaddr, error)
NetAddrsListen func(context.Context) (MultiaddrSlice, error)
}
}
@ -27,7 +26,7 @@ func (c *Struct) NetConnect(ctx context.Context, p peer.AddrInfo) error {
return c.Internal.NetConnect(ctx, p)
}
func (c *Struct) NetAddrsListen(ctx context.Context) ([]ma.Multiaddr, error) {
func (c *Struct) NetAddrsListen(ctx context.Context) (MultiaddrSlice, error) {
return c.Internal.NetAddrsListen(ctx)
}

28
api/types.go Normal file
View File

@ -0,0 +1,28 @@
package api
import (
"encoding/json"
ma "github.com/multiformats/go-multiaddr"
)
// TODO: check if this exists anywhere else
type MultiaddrSlice []ma.Multiaddr
func (m *MultiaddrSlice) UnmarshalJSON(raw []byte) (err error) {
var temp []string
if err := json.Unmarshal(raw, &temp); err != nil {
return err
}
res := make([]ma.Multiaddr, len(temp))
for i, str := range temp {
res[i], err = ma.NewMultiaddr(str)
if err != nil {
return err
}
}
*m = res
return nil
}
var _ json.Unmarshaler = new(MultiaddrSlice)

View File

@ -45,7 +45,7 @@ func (a *API) NetConnect(ctx context.Context, p peer.AddrInfo) error {
return a.Host.Connect(ctx, p)
}
func (a *API) NetAddrsListen(context.Context) ([]ma.Multiaddr, error) {
func (a *API) NetAddrsListen(context.Context) (api.MultiaddrSlice, error) {
return a.Host.Addrs(), nil
}