3

I would love to be able to use Go-IPFS within my Go program, however it is totally undocumented. This is where my reasearch lead me:

package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"

    "gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit/files"

    "github.com/ipfs/go-ipfs/core"
    "github.com/ipfs/go-ipfs/core/coreunix"
)

func main() {
    ctx := context.Background()

    node, err := core.NewNode(ctx, &core.BuildCfg{})
    if err != nil {
        log.Fatalf("Failed to start IPFS node: %v", err)
    }
    reader, err := coreunix.Cat(ctx, node, "QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB")
    if err != nil {
        log.Fatalf("Failed to look up IPFS welcome page: %v", err)
    }
    blob, err := ioutil.ReadAll(reader)
    if err != nil {
        log.Fatalf("Failed to retrieve IPFS welcome page: %v", err)
    }
    fmt.Println(string(blob))
}

However I am not sure about the difference of

context.Background() Vs context.TODO() Vs context.WithCancel(context.Background()).

And most importantly, how can choose where IPFS will put the IPFS repo and make sure it also initializes it?

How can I enable and use Pubsub along with its commands subscribe and publish?

How can I add and pin a file to IPFS with the possibility to also input a stream for big files?

Is coreunix.Cat suitable to read files with a stream as well?

How can I keep the node "listening" like when you run the ipfs daemon from the CLI and have everything runnng on all the ports like webui, swarm, etc.?

How about this to add files? Does this use streams or reads the entire file into memory? How can this be improved?

func addFile(ctx *context.Context, node *core.IpfsNode, path *string) error {
    file, err := os.Open(*path)
    if err != nil {
        return err
    }
    adder, err := coreunix.NewAdder(*ctx, node.Pinning, node.Blockstore, node.DAG)
    if err != nil {
        return err
    }
    filename := filepath.Base(*path)
    fileReader := files.NewReaderFile(filename, filename, file, nil)
    adder.AddFile(fileReader)
    adder.PinRoot()
    return nil
}
Aurelius
  • 689
  • 1
  • 6
  • 16

1 Answers1

2

You may want to breakdown your question into smaller pieces, I have been playing with a source code of go-ipfs for a while and here's the general instruction I could give you:

  1. Most of the data structures like, context, DAG, IPFSNode and so on are defined in form of go structures, and you should be able to find them in gx/.../... directory where also you should be able to see detailed information about each variable used ( simple string search through the directory should get you to your needed source file)
  2. All the methods are defined in folder github.com/../.. directory
  3. Clear the concept of pointers as they are using pointers most of the time to pass parameters to functions