-
Notifications
You must be signed in to change notification settings - Fork 1
/
record.go
66 lines (57 loc) · 1.49 KB
/
record.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package logger
import (
"encoding/json"
"github.com/gildas/go-errors"
)
// Record is the map that contains all records of a log entry
//
// If the value at a key is a func() interface the func will be called when the record is marshaled
type Record map[string]interface{}
// NewRecord creates a new empty record
func NewRecord() Record {
return Record(make(map[string]interface{}))
}
// Set sets the key and value if not yet set
func (record Record) Set(key string, value interface{}) Record {
if value == nil {
return record
}
if _, ok := record[key]; !ok {
record[key] = value
}
return record
}
// Merge merges a source Record into this Record
//
// values already set in this record cannot be overridden
func (record Record) Merge(source Record) Record {
for key, value := range source {
record.Set(key, value)
}
return record
}
// MarshalJSON marshals this into JSON
func (record Record) MarshalJSON() ([]byte, error) {
if len(record) == 0 {
return []byte("null"), nil
}
buffer := make(map[string]interface{}, len(record))
for k, v := range record {
switch v := v.(type) {
case func() interface{}:
buffer[k] = v()
default:
buffer[k] = v
}
}
return json.Marshal(buffer)
}
// UnmarshalJSON unmarshals JSON into this
func (record *Record) UnmarshalJSON(payload []byte) error {
var placeholder map[string]interface{}
if err := json.Unmarshal(payload, &placeholder); err != nil {
return errors.JSONUnmarshalError.Wrap(err)
}
*record = Record(placeholder)
return nil
}