-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5dc634b
commit eb58005
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package common | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
"github.com/libp2p/go-libp2p/core/host" | ||
"github.com/libp2p/go-libp2p/core/peer" | ||
"github.com/libp2p/go-libp2p/p2p/protocol/ping" | ||
) | ||
|
||
type Pinger interface { | ||
PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error) | ||
} | ||
|
||
type defaultPingImpl struct { | ||
host host.Host | ||
} | ||
|
||
func NewDefaultPinger(host host.Host) Pinger { | ||
return &defaultPingImpl{ | ||
host: host, | ||
} | ||
} | ||
|
||
func (d *defaultPingImpl) PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error) { | ||
pingResultCh := ping.Ping(ctx, d.host, peerID) | ||
select { | ||
case <-ctx.Done(): | ||
return 0, ctx.Err() | ||
case r := <-pingResultCh: | ||
if r.Error != nil { | ||
return 0, r.Error | ||
} | ||
return r.RTT, nil | ||
} | ||
} |