以编程方式使用Go-IPFS

时间:2018-09-05 07:44:36

标签: go ipfs

我希望能够在Go程序中使用Go-IPFS,但是它完全没有记载。这是我的研究引导我的地方:

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))
}

但是我不确定

的区别

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

最重要的是,如何选择IPFS将IPFS存储库放置在何处并确保它也对其进行初始化?

如何启用和使用Pubsub及其命令subscribepublish

如何添加文件并将其固定到IPFS,并且还可以为大文件输入流?

coreunix.Cat也适合通过流读取文件吗?

如何像在CLI中运行ipfs守护程序并使节点在webui,swarm等所有端口上运行一样,使节点保持“监听”状态?

如何添加文件?这是否使用流或将整个文件读入内存?如何改善呢?

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
}

1 个答案:

答案 0 :(得分:2)

您可能希望将问题分解成更小的部分,一段时间以来,我一直在使用go-ipfs的源代码,这是我可以给您的一般说明:

  1. 大多数数据结构(如上下文,DAG,IPFSNode等)以go结构的形式定义,您应该能够在gx / ... / ...目录中找到它们能够查看有关所使用的每个变量的详细信息(通过目录进行简单的字符串搜索即可将您带到所需的源文件)
  2. 所有方法都在文件夹github.com/../ ..目录中定义
  3. 清除指针的概念,因为它们大多数时候都使用指针将参数传递给函数