Use custom time format

This commit is contained in:
Julian Kornberger 2016-03-20 17:10:39 +01:00
parent d4a9a169f1
commit 808135904f
3 changed files with 59 additions and 4 deletions

25
jsontime/jsontime.go Normal file
View File

@ -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
}

29
jsontime/jsontime_test.go Normal file
View File

@ -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)
}

View File

@ -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]