Home > database >  Undefined: ctx was encountered while running go libp2p
Undefined: ctx was encountered while running go libp2p

Time:01-03

The code is following,it is the an offical demo of go-libp2p.And I didn't encounter any other references or undefined errors

    // if a remote peer has been passed on the command line, connect to it
    // and send it 5 ping messages, otherwise wait for a signal to stop
    if len(os.Args) > 1 {
        addr, err := multiaddr.NewMultiaddr(os.Args[1])
        if err != nil {
            panic(err)
        }
        peer, err := peerstore.AddrInfoFromP2pAddr(addr)
        if err != nil {
            panic(err)
        }
        if err := node.Connect(ctx, *peer); err != nil {
            panic(err)
        }
        fmt.Println("sending 5 ping messages to", addr)

The import is following:

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "github.com/libp2p/go-libp2p"
    peerstore "github.com/libp2p/go-libp2p-core/peer"
    "github.com/libp2p/go-libp2p/p2p/protocol/ping"
    multiaddr "github.com/multiformats/go-multiaddr"
)

CodePudding user response:

Looks like you are following the "Getting Started" tutorial. You'll need to import context and prior to the code block in your question, you'll need to create a context:

// create context
ctx:=context.Background()

// if a remote peer has been passed on the command line, connect to it
// and send it 5 ping messages, otherwise wait for a signal to stop
if len(os.Args) > 1 {
    addr, err := multiaddr.NewMultiaddr(os.Args[1])
    if err != nil {
        panic(err)
    }
    peer, err := peerstore.AddrInfoFromP2pAddr(addr)
    if err != nil {
        panic(err)
    }
    if err := node.Connect(ctx, *peer); err != nil {
        panic(err)
    }
    fmt.Println("sending 5 ping messages to", addr)
  • Related