Jun 14, 2024 by Arnaud Stoz | 378 views
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.
The IPFS-API module contain only one package: the client package.
The Client package contains three simple functions:
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 connects 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