aboutsummaryrefslogtreecommitdiff
path: root/cisa
diff options
context:
space:
mode:
Diffstat (limited to 'cisa')
-rw-r--r--cisa/date.go27
-rw-r--r--cisa/date_test.go64
2 files changed, 90 insertions, 1 deletions
diff --git a/cisa/date.go b/cisa/date.go
index b36b73c..b3b6528 100644
--- a/cisa/date.go
+++ b/cisa/date.go
@@ -1,6 +1,7 @@
package cisa
import (
+ "encoding/json"
"fmt"
"regexp"
"strconv"
@@ -135,5 +136,29 @@ func (me Date) String() string {
y, m, d := me.GetComponents()
// return string
- return fmt.Sprintf("%d-%d-%d", y, m, d)
+ return fmt.Sprintf("%04d-%02d-%02d", y, m, d)
+}
+
+// Unmarshal date from JSON string.
+func (me *Date) UnmarshalJSON(b []byte) error {
+ // decode json string
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+
+ // create date
+ d, err := NewDate([]byte(s))
+ if err != nil {
+ return err
+ }
+
+ // save result, return success
+ *me = d
+ return nil
+}
+
+// Marshal Date as JSON string.
+func (d Date) MarshalJSON() ([]byte, error) {
+ return json.Marshal(d.String())
}
diff --git a/cisa/date_test.go b/cisa/date_test.go
index c64f618..47e152e 100644
--- a/cisa/date_test.go
+++ b/cisa/date_test.go
@@ -1,6 +1,7 @@
package cisa
import (
+ "encoding/json"
"fmt"
"reflect"
"testing"
@@ -308,3 +309,66 @@ func TestString(t *testing.T) {
})
}
}
+
+func TestDateUnmarshalJSON(t *testing.T) {
+ passTests := []struct {
+ val string
+ exp string
+ } {
+ { `"2022-02-03"`, "2022-02-03" },
+ }
+
+ for _, test := range(passTests) {
+ var got Date
+ if err := json.Unmarshal([]byte(test.val), &got); err != nil {
+ t.Error(err)
+ } else if got.String() != test.exp {
+ t.Errorf("got \"%s\", exp \"%s\"", got.String(), test.exp)
+ }
+ }
+
+ failTests := []struct {
+ name string
+ val string
+ } {
+ { "fail-str", "asdf" },
+ { "fail-parse", "\"asdf\"" },
+ }
+
+ for _, test := range(failTests) {
+ t.Run(test.name, func(t *testing.T) {
+ var got Date
+ if err := got.UnmarshalJSON([]byte(test.val)); err == nil {
+ t.Errorf("got \"%v\" exp error", got)
+ }
+ })
+ }
+
+}
+
+func TestDateMarshalJSON(t *testing.T) {
+ tests := []struct {
+ val string
+ exp string
+ } {
+ { "2022-10-31", `"2022-10-31"` },
+ }
+
+ for _, test := range(tests) {
+ t.Run(test.val, func(t *testing.T) {
+ // create date
+ dt, err := NewDate([]byte(test.val))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ // get/check string
+ if got, err := dt.MarshalJSON(); err != nil {
+ t.Error(err)
+ } else if string(got) != test.exp {
+ t.Errorf("got \"%s\", exp \"%s\"", got, test.exp)
+ }
+ })
+ }
+}