diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..022b34e --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/pmorelli92/maybe + +go 1.16 diff --git a/int.go b/int.go new file mode 100644 index 0000000..98e61f2 --- /dev/null +++ b/int.go @@ -0,0 +1,34 @@ +package maybe + +import "encoding/json" + +type Int struct { + Value int + HasValue bool +} + +func (ms *Int) UnmarshalJSON(data []byte) error { + var s *int + if err := json.Unmarshal(data, &s); err != nil { + return err + } + + if s != nil { + *ms = Int{ + Value: *s, + HasValue: true, + } + } + + return nil +} + +func (ms Int) MarshalJSON() ([]byte, error) { + var s *int + + if ms.HasValue { + s = &ms.Value + } + + return json.Marshal(s) +} diff --git a/string.go b/string.go new file mode 100644 index 0000000..15aa94f --- /dev/null +++ b/string.go @@ -0,0 +1,34 @@ +package maybe + +import "encoding/json" + +type String struct { + Value string + HasValue bool +} + +func (ms *String) UnmarshalJSON(data []byte) error { + var s *string + if err := json.Unmarshal(data, &s); err != nil { + return err + } + + if s != nil { + *ms = String{ + Value: *s, + HasValue: true, + } + } + + return nil +} + +func (ms String) MarshalJSON() ([]byte, error) { + var s *string + + if ms.HasValue { + s = &ms.Value + } + + return json.Marshal(s) +}