瀏覽代碼

fix: potential slice append issue (#2560)

Kevin Wan 2 年之前
父節點
當前提交
7eb6aae949
共有 2 個文件被更改,包括 21 次插入1 次删除
  1. 4 1
      core/logx/fields.go
  2. 17 0
      core/logx/fields_test.go

+ 4 - 1
core/logx/fields.go

@@ -31,7 +31,10 @@ func AddGlobalFields(fields ...LogField) {
 func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
 	if val := ctx.Value(fieldsContextKey); val != nil {
 		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)
 		}
 	}
 

+ 17 - 0
core/logx/fields_test.go

@@ -4,6 +4,7 @@ import (
 	"bytes"
 	"context"
 	"encoding/json"
+	"strconv"
 	"sync"
 	"sync/atomic"
 	"testing"
@@ -67,6 +68,22 @@ func TestWithFieldsAppend(t *testing.T) {
 	}, 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) {
 	b.ReportAllocs()