pgtype
pgtype copied to clipboard
Implement json.Marshaller interface for Inet, Macaddr (et al.)
Application JSON data coming in (or going out) should not know (or reveal) anything about our underlying implementation model. For a given struct like:
type My struct {
IP pgtype.Inet
MAC pgtype.Macaddr
}
Populated accordingly, it would be reasonable for json.Marshall to deliver bytes equivalent to (for example):
{"IP":"192.0.2.1/32","MAC":"00:0a:95:9d:68:16"}
Symmetrically, json.Unmarshal should be able reconstitute the struct from the serialized JSON. Can probably submit a PR for some of this if you concur. Currently that would give an error like:
json: cannot unmarshal string into Go struct field My.IP of type pgtype.Inet
I think that would work.
Only thing to watch out for is ambiguous values that can't be round-tripped or things that don't have an obvious JSON representation. That has been an obstacle for JSON marshalling support for some other types. But off the top of my head I don't see any issues here.