fix: potential slice append issue (#2560)

master
Kevin Wan 2 years ago committed by GitHub
parent 07128213d6
commit 7eb6aae949
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -31,7 +31,10 @@ func AddGlobalFields(fields ...LogField) {
func ContextWithFields(ctx context.Context, fields ...LogField) context.Context { func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
if val := ctx.Value(fieldsContextKey); val != nil { if val := ctx.Value(fieldsContextKey); val != nil {
if arr, ok := val.([]LogField); ok { if arr, ok := val.([]LogField); ok {
return context.WithValue(ctx, fieldsContextKey, append(arr, fields...)) allFields := make([]LogField, 0, len(arr)+len(fields))
allFields = append(allFields, arr...)
allFields = append(allFields, fields...)
return context.WithValue(ctx, fieldsContextKey, allFields)
} }
} }

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"strconv"
"sync" "sync"
"sync/atomic" "sync/atomic"
"testing" "testing"
@ -67,6 +68,22 @@ func TestWithFieldsAppend(t *testing.T) {
}, fields) }, fields)
} }
func TestWithFieldsAppendCopy(t *testing.T) {
const count = 10
ctx := context.Background()
for i := 0; i < count; i++ {
ctx = ContextWithFields(ctx, Field(strconv.Itoa(i), 1))
}
af := Field("foo", 1)
bf := Field("bar", 2)
ctxa := ContextWithFields(ctx, af)
ctxb := ContextWithFields(ctx, bf)
assert.EqualValues(t, af, ctxa.Value(fieldsContextKey).([]LogField)[count])
assert.EqualValues(t, bf, ctxb.Value(fieldsContextKey).([]LogField)[count])
}
func BenchmarkAtomicValue(b *testing.B) { func BenchmarkAtomicValue(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()

Loading…
Cancel
Save