diff options
Diffstat (limited to 'lib/containers')
-rw-r--r-- | lib/containers/optional.go | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/containers/optional.go b/lib/containers/optional.go index 3055308..c0e7b32 100644 --- a/lib/containers/optional.go +++ b/lib/containers/optional.go @@ -4,7 +4,33 @@ package containers +import ( + "encoding/json" +) + type Optional[T any] struct { OK bool Val T } + +var ( + _ json.Marshaler = Optional[bool]{} + _ json.Unmarshaler = (*Optional[bool])(nil) +) + +func (o Optional[T]) MarshalJSON() ([]byte, error) { + if o.OK { + return json.Marshal(o.Val) + } else { + return []byte("null"), nil + } +} + +func (o *Optional[T]) UnmarshalJSON(dat []byte) error { + if string(dat) == "null" { + *o = Optional[T]{} + return nil + } + o.OK = true + return json.Unmarshal(dat, &o.Val) +} |