/
regutil.go
104 lines (89 loc) 路 2.28 KB
/
regutil.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package regutil
import (
"encoding/base32"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"github.com/srnbckr/ipdr/netutil"
cid "github.com/ipfs/go-cid"
base58 "github.com/jbenet/go-base58"
mbase "github.com/multiformats/go-multibase"
)
// DockerizeHash does base58 to base32 conversion
func DockerizeHash(base58Hash string) string {
re := regexp.MustCompile(`(/ipfs/)?(.*)`)
matches := re.FindStringSubmatch(base58Hash)
base58Hash = matches[len(matches)-1]
decodedB58 := base58.Decode(base58Hash)
b32str := base32.StdEncoding.EncodeToString(decodedB58)
end := len(b32str)
if end > 0 {
end = end - 1
}
// remove padding
return strings.ToLower(b32str[0:end])
}
// IpfsifyHash does base32 to base58 conversion
func IpfsifyHash(base32Hash string) string {
decodedB32, err := base32.StdEncoding.DecodeString(strings.ToUpper(base32Hash) + "=")
if err != nil {
return ""
}
return base58.Encode(decodedB32)
}
// IpfsURL constructs IPFS gateway URL
func IpfsURL(gw string, s []string) string {
return fmt.Sprintf("%s/ipfs/%s", gw, strings.Join(s, "/"))
}
func toCidV0(c cid.Cid) (cid.Cid, error) {
if c.Type() != cid.DagProtobuf {
return cid.Cid{}, fmt.Errorf("can't convert non-protobuf nodes to cidv0")
}
return cid.NewCidV0(c.Hash()), nil
}
func toCidV1(c cid.Cid) (cid.Cid, error) {
return cid.NewCidV1(c.Type(), c.Hash()), nil
}
// ToB58 returns base58 encoded string if s is a valid cid
func ToB58(s string) string {
c, err := cid.Decode(s)
if err == nil {
return c.Hash().B58String()
}
return ""
}
// ToB32 returns base32 encoded string if s is a valid cid
func ToB32(s string) string {
c, err := cid.Decode(s)
if err != nil {
return ""
}
c1, err := toCidV1(c)
if err != nil {
return ""
}
b32, err := c1.StringOfBase(mbase.Base32)
if err != nil {
return ""
}
return b32
}
// Dig interrogates registry server. It performs CID lookups and shows the response.
func Dig(gw string, short bool, name string) (string, error) {
uri := fmt.Sprintf("http://%s/dig?q=%s&short=%v", gw, name, short)
resp, err := netutil.Get(uri)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf(resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}