Skip to content

Commit

Permalink
Add special formatting for CIDs and Multiaddrs
Browse files Browse the repository at this point in the history
Cid objects always serialize to JSON as `{"/": "<cid string>"}` (https://github.com/ipfs/go-cid/blob/078355866b1dda1658b5fdc5496ed7e25fdcf883/cid.go#L407-L415). There's no obvious way to detect what any type's serialization behavior might be, so we need a special case explicitly for CIDs here.

Also specially calls out Multiaddrs. It doesn't appear that we have any other interfaces or pointer types besides these two that wind up in response schemas. I don't know that string checking on the type is really the best way to do this, but it seemed expendient and avoids needing to depend on CID and Multiaddr packages and make sure they stay in sync with the version of IPFS we are working against.

There is also some discussion here (ipfs/kubo#5077) on whether this is the right formatting for CIDs. For now, I'm including it here because I heard plenty of complaints about the usefulness and accuracy of these docs from users. The output of this tool is preceived as documentation and not a spec, so I think it's right that it shows what IPFS actually *does,* not just what we think it *ought* to. (If we wanted this to be more like a spec, we need a way to annotate it for users to explain the difference between implementation and spec.)

License: MIT
Signed-off-by: Rob Brackett <[email protected]>
  • Loading branch information
Mr0grog committed Jun 11, 2018
1 parent c92cd7f commit bb109bf
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,22 @@ func interfaceToJsonish(t reflect.Type, i int) string {
case reflect.Invalid:
result.WriteString("null\n")
case reflect.Interface:
result.WriteString(insertIndent(i) + "\"<object>\"\n")
description := "\"<object>\""
// Handle types that should be called out specially
if t.String() == "multiaddr.Multiaddr" {
description = "\"<multiaddr-string>\""
}
result.WriteString(fmt.Sprintf("%s%s\n", insertIndent(i), description))
case reflect.Ptr:
if _, ok := t.MethodByName("String"); ok && countExported(t.Elem()) == 0 {
// CIDs have specialized JSON marshaling, see:
// https://github.com/ipfs/go-cid/blob/078355866b1dda1658b5fdc5496ed7e25fdcf883/cid.go#L407-L415
if t.String() == "*cid.Cid" {
result.WriteString(insertIndent(i) + "{ \"/\": \"<cid-string>\" }\n")
} else if _, ok := t.MethodByName("String"); ok && countExported(t.Elem()) == 0 {
return interfaceToJsonish(reflect.TypeOf(""), i)
} else {
return interfaceToJsonish(t.Elem(), i)
}
return interfaceToJsonish(t.Elem(), i)
case reflect.Map:
result.WriteString(insertIndent(i) + "{\n")
result.WriteString(insertIndent(i+IndentLevel) + fmt.Sprintf(`"<%s>": `, t.Key().Kind()))
Expand Down

0 comments on commit bb109bf

Please sign in to comment.