-
Notifications
You must be signed in to change notification settings - Fork 43
/
utils.go
89 lines (74 loc) · 1.87 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package ipfs
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/ipfs/go-cid"
chunker "github.com/ipfs/go-ipfs-chunker"
ipld "github.com/ipfs/go-ipld-format"
"github.com/ipfs/go-merkledag"
"github.com/ipfs/go-unixfs/importer/balanced"
"github.com/ipfs/go-unixfs/importer/helpers"
"github.com/ipfs/go-unixfs/importer/trickle"
mh "github.com/multiformats/go-multihash"
)
func GetFileHash(r io.Reader) (string, error) {
hashFun := "sha2-256"
prefix, err := merkledag.PrefixForCidVersion(1)
if err != nil {
return "", fmt.Errorf("bad CID Version: %s", err)
}
hashFunCode, ok := mh.Names[strings.ToLower(hashFun)]
if !ok {
return "", fmt.Errorf("unrecognized hash function: %s", hashFun)
}
prefix.MhType = hashFunCode
prefix.MhLength = -1
prefix.Codec = cid.DagProtobuf
dagServ := NewDagService()
dbp := helpers.DagBuilderParams{
Dagserv: dagServ,
RawLeaves: true,
Maxlinks: helpers.DefaultLinksPerBlock,
NoCopy: false,
CidBuilder: &prefix,
}
chnk, err := chunker.FromString(r, "")
if err != nil {
return "", err
}
dbh, err := dbp.New(chnk)
if err != nil {
return "", err
}
layout := "trickle"
var n ipld.Node
switch layout {
case "trickle":
n, err = trickle.Layout(dbh)
case "balanced", "":
n, err = balanced.Layout(dbh)
default:
return "", errors.New("invalid Layout")
}
return n.Cid().String(), nil
}
func DownloadIpfsItem(ctx context.Context, gatewayUrl string, cid cid.Cid) (io.ReadCloser, error) {
url := fmt.Sprintf("%s/ipfs/%s", gatewayUrl, cid.String())
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
client := http.Client{}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to fetch item: status_code %d", resp.StatusCode)
}
return resp.Body, nil
}