Handel undefined Cid is JSON representation.

This commit is contained in:
Kevin Atkinson
2018-09-07 14:03:03 -04:00
parent 67a2bcf7e7
commit 46dd393ad1

10
cid.go
View File

@@ -404,10 +404,15 @@ func (c *Cid) UnmarshalJSON(b []byte) error {
obj := struct {
CidTarget string `json:"/"`
}{}
err := json.Unmarshal(b, &obj)
objptr := &obj
err := json.Unmarshal(b, &objptr)
if err != nil {
return err
}
if objptr == nil {
*c = Cid{}
return nil
}
if obj.CidTarget == "" {
return fmt.Errorf("cid was incorrectly formatted")
@@ -430,6 +435,9 @@ func (c *Cid) UnmarshalJSON(b []byte) error {
// Note that this formatting comes from the IPLD specification
// (https://github.com/ipld/specs/tree/master/ipld)
func (c Cid) MarshalJSON() ([]byte, error) {
if !c.Defined() {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("{\"/\":\"%s\"}", c.String())), nil
}