Skip to content

Commit

Permalink
Added FieldsFromContext method
Browse files Browse the repository at this point in the history
  • Loading branch information
asticode committed Nov 13, 2020
1 parent 5184b8c commit cd59a08
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
13 changes: 13 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ func fieldsFromContext(ctx context.Context) *contextFields {
return v
}

func FieldsFromContext(ctx context.Context) (fs map[string]interface{}) {
if cfs := fieldsFromContext(ctx); cfs != nil {
cfs.m.Lock()
fs = make(map[string]interface{})
for k, v := range cfs.fs {
fs[k] = v
}
cfs.m.Unlock()
return
}
return
}

func ContextWithField(ctx context.Context, k string, v interface{}) context.Context {
return ContextWithFields(ctx, map[string]interface{}{k: v})
}
Expand Down
4 changes: 2 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func TestContext(t *testing.T) {
"k2": "v2",
}
ctx := ContextWithFields(context.Background(), fs)
if g := fieldsFromContext(ctx); !reflect.DeepEqual(fs, g.fs) {
t.Errorf("expected %+v, got %+v", fs, g.fs)
if g := FieldsFromContext(ctx); !reflect.DeepEqual(fs, g) {
t.Errorf("expected %+v, got %+v", fs, g)
}
}

0 comments on commit cd59a08

Please sign in to comment.