From 808135904fe6bea3e33b7360d8e9ae853c1839cb Mon Sep 17 00:00:00 2001 From: Julian Kornberger Date: Sun, 20 Mar 2016 17:10:39 +0100 Subject: [PATCH] Use custom time format --- jsontime/jsontime.go | 25 +++++++++++++++++++++++++ jsontime/jsontime_test.go | 29 +++++++++++++++++++++++++++++ models/nodes.go | 9 +++++---- 3 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 jsontime/jsontime.go create mode 100644 jsontime/jsontime_test.go diff --git a/jsontime/jsontime.go b/jsontime/jsontime.go new file mode 100644 index 0000000..51aa8a3 --- /dev/null +++ b/jsontime/jsontime.go @@ -0,0 +1,25 @@ +package jsontime + +import ( + "time" +) + +const TimeFormat = "2006-01-02T15:04:05" + +type Time time.Time + +func Now() Time { + return Time(time.Now()) +} + +func (t Time) MarshalJSON() ([]byte, error) { + stamp := `"` + time.Time(t).Format(TimeFormat) + `"` + return []byte(stamp), nil +} + +func (t Time) UnmarshalJSON(data []byte) (err error) { + if nativeTime, err := time.Parse(TimeFormat, string(data)); err == nil { + t = Time(nativeTime) + } + return +} diff --git a/jsontime/jsontime_test.go b/jsontime/jsontime_test.go new file mode 100644 index 0000000..040089d --- /dev/null +++ b/jsontime/jsontime_test.go @@ -0,0 +1,29 @@ +package jsontime + +import ( + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestMarshalTime(t *testing.T) { + assert := assert.New(t) + + nativeTime, err := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00") + assert.Nil(err) + + json, err := Time(nativeTime).MarshalJSON() + assert.Nil(err) + + assert.Equal(`"2012-11-01T22:08:41"`, string(json)) +} + +func TestUnmarshalTime(t *testing.T) { + assert := assert.New(t) + jsonTime := Time{} + + err := json.Unmarshal([]byte(`"2012-11-01T22:08:41"`), &jsonTime) + assert.Nil(err) +} diff --git a/models/nodes.go b/models/nodes.go index f9e636b..03b862c 100644 --- a/models/nodes.go +++ b/models/nodes.go @@ -9,12 +9,13 @@ import ( "time" "github.com/FreifunkBremen/respond-collector/data" + "github.com/FreifunkBremen/respond-collector/jsontime" ) // Node struct type Node struct { - Firstseen time.Time `json:"firstseen"` - Lastseen time.Time `json:"lastseen"` + Firstseen jsontime.Time `json:"firstseen"` + Lastseen jsontime.Time `json:"lastseen"` Statistics *data.Statistics `json:"statistics"` Nodeinfo *data.NodeInfo `json:"nodeinfo"` Neighbours *data.Neighbours `json:"-"` @@ -27,7 +28,7 @@ type NodeElement struct { // Nodes struct: cache DB of Node's structs type Nodes struct { Version int `json:"version"` - Timestamp time.Time `json:"timestamp"` + Timestamp jsontime.Time `json:"timestamp"` List map[string]*Node `json:"nodes"` // the current nodemap, indexed by node ID sync.Mutex } @@ -44,7 +45,7 @@ func NewNodes() *Nodes { // Update a Node func (nodes *Nodes) Update(nodeID string, res *data.ResponseData) { - now := time.Now() + now := jsontime.Now() nodes.Lock() node, _ := nodes.List[nodeID]