Search code examples
goipfs

how to get peers list using go-ipfs-api?


I am a Newbie of ipfs and go, trying to get the ipfs information using go-ipfs-api. Following is my code:

package main

import (
         "fmt"
         "context"
         "os"
         "net/http"
         "github.com/prometheus/client_golang/prometheus"
         "github.com/prometheus/client_golang/prometheus/promhttp"
         "github.com/ipfs/go-ipfs-api"
)
 
 var sh *shell.Shell
 
 func main() {
         sh := shell.NewShell("localhost:5001")
         cid, err := sh.SwarmPeers()
         if err != nil {
                 fmt.Fprintf(os.Stderr, "error: %s", err)
                 os.Exit(1)
         }
         fmt.Printf("added %s", cid)
 }

This sh.SwarmPeers need some context as a parameter. I am not getting what parameter do I need to pass to get the peers list. Also, which API functions should I use to get the total number of files and the total size of files that exist on ipfs? Please help. If any tutorials are present please share. It will help me to understand using other functions. Any help would be appreciated.


Solution

  • The context is a Golang context which helps track things like deadlines or cancellations of operations. In this case because you're making an HTTP call to your local IPFS daemon it's possible you might want to cancel the function because it's taking too long or your application no longer cares and the context lets you handle that use case.

    You can get a background context (i.e. lives forever and is never cancelled) via context.Background(). If you want to set a timeout on it you can pass that background context to context.WithTimeout. Checkout the Golang docs on context for more information.