forked from rs/zerolog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
46 lines (42 loc) · 1.11 KB
/
base.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
package json
type Encoder struct{}
// AppendKey appends a new key to the output JSON.
func (e Encoder) AppendKey(dst []byte, key string) []byte {
if len(dst) > 1 && dst[len(dst)-1] != '{' {
dst = append(dst, ',')
}
dst = e.AppendString(dst, key)
return append(dst, ':')
}
// AppendError encodes the error string to json and appends
// the encoded string to the input byte slice.
func (e Encoder) AppendError(dst []byte, err error) []byte {
if err == nil {
return append(dst, `null`...)
}
return e.AppendString(dst, err.Error())
}
// AppendErrors encodes the error strings to json and
// appends the encoded string list to the input byte slice.
func (e Encoder) AppendErrors(dst []byte, errs []error) []byte {
if len(errs) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
if errs[0] != nil {
dst = e.AppendString(dst, errs[0].Error())
} else {
dst = append(dst, "null"...)
}
if len(errs) > 1 {
for _, err := range errs[1:] {
if err == nil {
dst = append(dst, ",null"...)
continue
}
dst = e.AppendString(append(dst, ','), err.Error())
}
}
dst = append(dst, ']')
return dst
}