-
-
Save MarcoPolo/8c9620759446c713f7d7638713203d88 to your computer and use it in GitHub Desktop.
An interactive go-libp2p node. Pings a provided multiaddr. Start it and type: ping <multiaddr-with-p2p>
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
package main | |
import ( | |
"bufio" | |
"context" | |
"fmt" | |
"os" | |
"strings" | |
"github.com/libp2p/go-libp2p" | |
"github.com/libp2p/go-libp2p/core/peer" | |
"github.com/libp2p/go-libp2p/p2p/protocol/ping" | |
) | |
func main() { | |
return | |
h, err := libp2p.New() | |
if err != nil { | |
panic(err) | |
} | |
defer h.Close() | |
// Read line from stdin: | |
reader := bufio.NewReader(os.Stdin) | |
for { | |
input, err := reader.ReadString('\n') | |
if err != nil { | |
fmt.Println("err reading input:", err) | |
continue | |
} | |
parts := strings.SplitN(input, " ", 2) | |
switch parts[0] { | |
case "ping": | |
// Ping the peer: | |
multiaddrStr := strings.Trim(parts[1], " \n") | |
peerAddr, err := peer.AddrInfoFromString(multiaddrStr) | |
if err != nil { | |
fmt.Println("error parsing peer address:", err) | |
continue | |
} | |
err = h.Connect(context.Background(), *peerAddr) | |
if err != nil { | |
fmt.Println("error connecting to peer:", err) | |
continue | |
} | |
ctx, cancel := context.WithCancel(context.Background()) | |
p := ping.Ping(ctx, h, peerAddr.ID) | |
res := <-p | |
cancel() | |
if res.Error != nil { | |
fmt.Println("ping error:", res.Error) | |
continue | |
} | |
fmt.Println("ping result:", res.RTT) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment