key marshalling + b58 encoding
Juan Batiz-Benet committed
Oct 22, 2014 at 02:54 UTC
5d86ce56acfabba1d8a85e3db6a756442ff46fdb
1 file changed
+42
util/key.go
+42
@@ -1,6 +1,9 @@
1
package util
2
3
import (
4
+ "encoding/json"
5
+ "fmt"
6
+
7
b58 "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-base58"
8
ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
9
mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
@@ -15,7 +18,23 @@ func (k Key) String() string {
18
}
19
20
// Pretty returns Key in a b58 encoded string
21
+// TODO: deprecate Pretty. bad name.
22
func (k Key) Pretty() string {
23
+ return k.B58String()
24
+}
25
+
26
+// B58String returns Key in a b58 encoded string
27
+func (k Key) B58String() string {
28
+ return B58KeyEncode(k)
29
+}
30
+
31
+// B58KeyDecode returns Key from a b58 encoded string
32
+func B58KeyDecode(s string) Key {
33
+ return Key(string(b58.Decode(s)))
34
+}
35
+
36
+// B58KeyEncode returns Key in a b58 encoded string
37
+func B58KeyEncode(k Key) string {
38
return b58.Encode([]byte(k))
39
}
40
@@ -24,6 +43,29 @@ func (k Key) DsKey() ds.Key {
43
return ds.NewKey(string(k))
44
}
45
46
+// UnmarshalJSON returns a JSON-encoded Key (string)
47
+func (k *Key) UnmarshalJSON(mk []byte) error {
48
+ var s string
49
+ err := json.Unmarshal(mk, &s)
50
+ if err != nil {
51
+ return err
52
+ }
53
+
54
+ *k = Key(string(b58.Decode(s)))
55
+ if len(*k) == 0 && len(s) > 2 { // if b58.Decode fails, k == ""
56
+ return fmt.Errorf("Key.UnmarshalJSON: invalid b58 string: %v", mk)
57
+ }
58
+ log.Info("Unmarshal in: %s \"%s\"", *k, s)
59
+ return nil
60
+}
61
+
62
+// MarshalJSON returns a JSON-encoded Key (string)
63
+func (k *Key) MarshalJSON() ([]byte, error) {
64
+ b, err := json.Marshal(b58.Encode([]byte(*k)))
65
+ log.Info("Marshal out: %s %s", *k, b)
66
+ return b, err
67
+}
68
+
69
// KeyFromDsKey returns a Datastore key
70
func KeyFromDsKey(dsk ds.Key) Key {
71
return Key(dsk.BaseNamespace())