Skip to content

Commit

Permalink
Add delete a baggage item in span
Browse files Browse the repository at this point in the history
  • Loading branch information
zacscoding committed Mar 15, 2021
1 parent fe3fa55 commit d24aa37
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
14 changes: 14 additions & 0 deletions span_context.go
Expand Up @@ -314,6 +314,7 @@ func (c *SpanContext) CopyFrom(ctx *SpanContext) {
}

// WithBaggageItem creates a new context with an extra baggage item.
// Delete a baggage item if provided blank value.
//
// The SpanContext is designed to be immutable and passed by value. As such,
// it cannot contain any locks, and should only hold immutable data, including baggage.
Expand All @@ -324,6 +325,19 @@ func (c *SpanContext) CopyFrom(ctx *SpanContext) {
// a trace), or it needs to do a copy-on-write, which is the approach taken here.
func (c SpanContext) WithBaggageItem(key, value string) SpanContext {
var newBaggage map[string]string
// unset baggage item
if value == "" {
if _, ok := c.baggage[key]; ok {
newBaggage = make(map[string]string, len(c.baggage))
for k, v := range c.baggage {
newBaggage[k] = v
}
delete(newBaggage, key)
} else {
newBaggage = c.baggage
}
return SpanContext{c.traceID, c.spanID, c.parentID, newBaggage, "", c.samplingState, c.remote}
}
if c.baggage == nil {
newBaggage = map[string]string{key: value}
} else {
Expand Down
10 changes: 10 additions & 0 deletions span_context_test.go
Expand Up @@ -79,6 +79,16 @@ func TestSpanContext_WithBaggageItem(t *testing.T) {
assert.Equal(t, map[string]string{"some-KEY": "Some-Other-Value"}, ctx.baggage)
}

func TestSpanContext_WithBaggageItem_Delete(t *testing.T) {
var ctx SpanContext
ctx = ctx.WithBaggageItem("some-KEY", "")
assert.Nil(t, ctx.baggage)
ctx = ctx.WithBaggageItem("some-KEY", "Some-Value")
assert.Equal(t, map[string]string{"some-KEY": "Some-Value"}, ctx.baggage)
ctx = ctx.WithBaggageItem("some-KEY", "")
assert.Equal(t, map[string]string{}, ctx.baggage)
}

func TestSpanContext_Flags(t *testing.T) {

var tests = map[string]struct {
Expand Down

0 comments on commit d24aa37

Please sign in to comment.