Skip to content

Commit

Permalink
Add baggage ForEach to avoid copies, and a test
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh MacDonald committed Dec 23, 2020
1 parent abe1454 commit 3b643a2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions baggage/baggage.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ func Set(ctx context.Context) label.Set {
return label.NewSet(values...)
}

// ForEach allows visiting the baggage values in a context without
// copying a slice.
func ForEach(ctx context.Context, f func(kv label.KeyValue) bool) {
baggage.MapFromContext(ctx).Foreach(f)
}

// Value returns the value related to key in the baggage of ctx. If no
// value is set, the returned label.Value will be an uninitialized zero-value
// with type INVALID.
Expand Down
21 changes: 21 additions & 0 deletions baggage/baggage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"context"
"testing"

"github.com/stretchr/testify/require"

"go.opentelemetry.io/otel/internal/baggage"
"go.opentelemetry.io/otel/label"
)
Expand Down Expand Up @@ -84,3 +86,22 @@ func TestBaggage(t *testing.T) {
t.Fatal("WithoutBaggage failed to clear baggage")
}
}

func TestForEach(t *testing.T) {
ctx := ContextWithValues(
context.Background(),
label.String("A", "B"),
label.String("C", "D"),
)

out := map[string]string{}
ForEach(ctx, func(kv label.KeyValue) bool {
out[string(kv.Key)] = kv.Value.Emit()
return true
})

require.EqualValues(t, map[string]string{
"A": "B",
"C": "D",
}, out)
}

0 comments on commit 3b643a2

Please sign in to comment.