Fix JSON when object is first to be pushed (#154)
When pushing an object to the logger, and this object was the first field added. Zerolog was outputting an invalid json blob, issuing an extra comma before the object. This patch ensure that JSON is still valid even if an object is pushed first to the logger. Fixes #152
This commit is contained in:
parent
1a2c7daec4
commit
9938a23cba
|
@ -373,12 +373,17 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
|
||||||
// AppendObjectData takes in an object that is already in a byte array
|
// AppendObjectData takes in an object that is already in a byte array
|
||||||
// and adds it to the dst.
|
// and adds it to the dst.
|
||||||
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {
|
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {
|
||||||
// Two conditions we want to put a ',' between existing content and
|
// Three conditions apply here:
|
||||||
// new content:
|
// 1. new content starts with '{' - which should be dropped OR
|
||||||
// 1. new content starts with '{' - which shd be dropped OR
|
// 2. new content starts with '{' - which should be replaced with ','
|
||||||
// 2. existing content has already other fields
|
// to separate with existing content OR
|
||||||
|
// 3. existing content has already other fields
|
||||||
if o[0] == '{' {
|
if o[0] == '{' {
|
||||||
o[0] = ','
|
if len(dst) == 0 {
|
||||||
|
o = o[1:]
|
||||||
|
} else {
|
||||||
|
o[0] = ','
|
||||||
|
}
|
||||||
} else if len(dst) > 1 {
|
} else if len(dst) > 1 {
|
||||||
dst = append(dst, ',')
|
dst = append(dst, ',')
|
||||||
}
|
}
|
||||||
|
|
|
@ -165,3 +165,23 @@ func Test_appendMac(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_appendObjectData(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
dst []byte
|
||||||
|
obj []byte
|
||||||
|
want []byte
|
||||||
|
}{
|
||||||
|
{[]byte{}, []byte(`{"foo":"bar"}`), []byte(`"foo":"bar"}`)},
|
||||||
|
{[]byte(`{"qux":"quz"`), []byte(`{"foo":"bar"}`), []byte(`{"qux":"quz","foo":"bar"}`)},
|
||||||
|
{[]byte{}, []byte(`"foo":"bar"`), []byte(`"foo":"bar"`)},
|
||||||
|
{[]byte(`{"qux":"quz"`), []byte(`"foo":"bar"`), []byte(`{"qux":"quz","foo":"bar"`)},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run("ObjectData", func(t *testing.T) {
|
||||||
|
if got := enc.AppendObjectData(tt.dst, tt.obj); !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Errorf("appendObjectData() = %s, want %s", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue