1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-04 23:40:26 +08:00

fix(p2p): handle error on parsing endpoint

This commit is contained in:
源文雨
2024-07-17 00:10:43 +09:00
parent 7d25f46813
commit 1c665c68fb
5 changed files with 19 additions and 14 deletions

View File

@@ -12,7 +12,7 @@ var (
ErrEndpointTypeMistatch = errors.New("endpoint type mismatch")
)
type Initializer func(endpoint string, configs ...any) EndPoint
type Initializer func(endpoint string, configs ...any) (EndPoint, error)
var factory syncx.Map[string, Initializer]
@@ -32,7 +32,7 @@ func NewEndPoint(network, endpoint string, configs ...any) (EndPoint, error) {
if !ok {
return nil, errors.New("network " + network + " not found")
}
return initializer(endpoint, configs...), nil
return initializer(endpoint, configs...)
}
type Conn interface {

View File

@@ -14,25 +14,27 @@ type Config struct {
ReceiveChannelSize int
}
func NewEndpoint(endpoint string, configs ...any) p2p.EndPoint {
func NewEndpoint(endpoint string, configs ...any) (p2p.EndPoint, error) {
return newEndpoint(endpoint, configs...)
}
func newEndpoint(endpoint string, configs ...any) *EndPoint {
func newEndpoint(endpoint string, configs ...any) (*EndPoint, error) {
var cfg *Config
if len(configs) == 0 || configs[0] == nil {
cfg = &Config{}
} else {
cfg = configs[0].(*Config)
}
addr, err := netip.ParseAddrPort(endpoint)
if err != nil {
return nil, err
}
return &EndPoint{
addr: net.TCPAddrFromAddrPort(
netip.MustParseAddrPort(endpoint),
),
addr: net.TCPAddrFromAddrPort(addr),
dialtimeout: cfg.DialTimeout,
peerstimeout: cfg.PeersTimeout,
recvchansize: cfg.ReceiveChannelSize,
}
}, nil
}
func init() {

View File

@@ -112,7 +112,7 @@ func (conn *Conn) accept() {
logrus.Info("[tcp] re-listen on", conn.addr)
continue
}
ep := newEndpoint(tcpconn.RemoteAddr().String(), &Config{
ep, _ := newEndpoint(tcpconn.RemoteAddr().String(), &Config{
DialTimeout: conn.addr.dialtimeout,
PeersTimeout: conn.addr.peerstimeout,
ReceiveChannelSize: conn.addr.recvchansize,

View File

@@ -7,10 +7,12 @@ import (
"github.com/fumiama/WireGold/gold/p2p"
)
func NewEndpoint(endpoint string, _ ...any) p2p.EndPoint {
return (*EndPoint)(net.UDPAddrFromAddrPort(
netip.MustParseAddrPort(endpoint),
))
func NewEndpoint(endpoint string, _ ...any) (p2p.EndPoint, error) {
addr, err := netip.ParseAddrPort(endpoint)
if err != nil {
return nil, err
}
return (*EndPoint)(net.UDPAddrFromAddrPort(addr)), nil
}
func init() {

View File

@@ -44,7 +44,8 @@ func (conn *Conn) String() string {
}
func (conn *Conn) LocalAddr() p2p.EndPoint {
return NewEndpoint((*net.UDPConn)(conn).LocalAddr().String())
ep, _ := NewEndpoint((*net.UDPConn)(conn).LocalAddr().String())
return ep
}
func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) {