Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created October 6, 2018 19:13
Show Gist options
  • Save miguelmota/f8d664453a4f6eb6528d0a37aab557f6 to your computer and use it in GitHub Desktop.
Save miguelmota/f8d664453a4f6eb6528d0a37aab557f6 to your computer and use it in GitHub Desktop.
Golang IPFS shell/cli example
package ipfsutil
import (
"bytes"
"fmt"
"io"
"log"
"time"
ipfs "github.com/ipfs/go-ipfs-api"
)
// Add adds data to IPFS
func Add(data []byte) (string, error) {
// my have ipfs daemon running first
shell := ipfs.NewLocalShell()
reader := bytes.NewReader(data)
hash, err := shell.Add(reader)
if err != nil {
log.Fatal(err)
}
return hash, nil
}
// AddFile adds a file to IPFS
func AddFile(file io.Reader) (string, error) {
// my have ipfs daemon running first
shell := ipfs.NewLocalShell()
var buf bytes.Buffer
if _, err := io.Copy(&buf, file); err != nil {
return "", err
}
fmt.Printf("adding to ipfs: %s\n", string(buf.Bytes()))
hash, err := shell.Add(file)
if err != nil {
log.Fatal(err)
}
return hash, nil
}
// Publish returns IPNS name
func Publish(hash string) (string, error) {
shell := ipfs.NewLocalShell()
keyName := "self"
resp, err := shell.PublishWithDetails(hash, keyName, time.Hour*100, time.Hour*100, false)
if err != nil {
return "", err
}
return resp.Name, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment