IPFS-API: a go IPFS RPC API client

Jun 14, 2024 by Arnaud Stoz | 233 views

Blockchain golang

https://cylab.be/blog/346/ipfs-api-a-go-ipfs-rpc-api-client

If you already research about web3 and decentralization, you probably stumbled on the Inter Planetary File System (IPFS). However if you wanted to use the API provided by the IPFS in one of your go program, you probably went crazy trying to understand how to use the API to finaly realize the documentation is not even up to date and refer to deprecated library. The IPFS-API module try to fill this gap and provide a basic yet simple to use package to interact with an IPFS RPC API endpoint.

Client package

The IPFS-API module contain only one package: the client package.

The Client package contains three simple functions:

  1. NewIPFSApi: used to initialized a new client to a given IPFS endpoint.
  2. Add: store a file to the IPFS network. Be aware that this file will be pinned by default.
  3. Cat: the exact twin of the IPFS cat command. Retrieve the content of a file based on its CID.

With those three simple functions, all basic operation can be achieved which mean uploading a file to the IPFS network and the retrieve that file based on it's CID.

Here is a very simple program to showcase the possibility of this small module. It first connect to a node running locally, then upload a test file and finally retrieve this file based on the CID.

package main

import (
    "fmt"
    "io"

    ipfsapi "github.com/stolab/ipfs-api/client"
)

func main() {
    //initialize the client
    client, err := ipfsapi.NewLocalApi()
    if err != nil {
        panic(err)
    }

    //add a file to the IPFS network and display its CID
    rep, err := client.Add("/tmp/test.txt")
    if err != nil {
        panic(err)
    }
    CID := rep.Hash
    fmt.Printf("CID of the uploaded package: %s\n", CID)

    //retrieved the file based on it's CID and display its content
    r, err := client.Cat(CID)
    if err != nil {
        panic(err)
    }
    defer r.Body.Close()
    byteContent, err := io.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Content of the file: %s\n", string(byteContent))
}

With this small module you can easily interact with IFPS node via the RPC API in all your go program.

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept