Skip to content

Instantly share code, notes, and snippets.

@meyer9
Created September 22, 2019 02:03
Show Gist options
  • Save meyer9/7cd0547d0e5c7d76d96068d0a9c5e75f to your computer and use it in GitHub Desktop.
Save meyer9/7cd0547d0e5c7d76d96068d0a9c5e75f to your computer and use it in GitHub Desktop.
IPFS code to retrieve a file
package main
import (
"context"
"fmt"
"image/jpeg"
"log"
"path/filepath"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/plugin/loader"
"github.com/ipfs/go-ipfs/repo/fsrepo"
"github.com/ipfs/interface-go-ipfs-core/path"
)
func main() {
ctx := context.Background()
plugins, err := loader.NewPluginLoader(filepath.Join("~/.ipfs/plugins"))
if err != nil {
log.Fatalf("error loading plugins: %s", err)
}
if err := plugins.Initialize(); err != nil {
log.Fatalf("error initializing plugins: %s", err)
}
if err := plugins.Inject(); err != nil {
log.Fatalf("error initializing plugins: %s", err)
}
// Basic ipfsnode setup
r, err := fsrepo.Open("~/.ipfs")
if err != nil {
log.Fatalf("error initializing fsrepo: %s", err)
}
cfg := &core.BuildCfg{
Repo: r,
Online: true,
}
nd, err := core.NewNode(ctx, cfg)
if err != nil {
log.Fatalf("error initializing new node: %s", err)
}
api, err := coreapi.NewCoreAPI(nd)
if err != nil {
log.Fatalf("error initializing core api: %s", err)
}
fileNode, err := api.Unixfs().Get(ctx, path.New("QmetHjTqTkziCfch1WPorNUTrWDHWEwuhZjRD4CnaZm146"))
if err != nil {
log.Fatalf("error retrieving file: %s", err)
}
if file, success := fileNode.(files.File); success {
image, err := jpeg.Decode(file)
if err != nil {
log.Fatalf("error parsing jpg: %s", err)
}
fmt.Printf("Got image with bounds: %d x %d!\n", image.Bounds().Dx(), image.Bounds().Dy())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment