diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a2e940c978..6f35c83d76d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Add the `"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc".WithGRPCConn` option so the exporter can reuse an existing gRPC connection. (#2002) - Added a new `schema` module to help parse Schema Files in OTEP 0152 format. (#2267) +- Added a new `MapCarrier` to the `go.opentelemetry.io/otel/propagation` package to hold propagated coss-cutting concerns as a `map[string]string` held in memory. (#2334) ## [1.1.0] - 2021-10-27 diff --git a/propagation/propagation.go b/propagation/propagation.go index 2f54532d9a7..c94438f73a5 100644 --- a/propagation/propagation.go +++ b/propagation/propagation.go @@ -40,6 +40,32 @@ type TextMapCarrier interface { // must never be done outside of a new major release. } +// MapCarrier is a TextMapCarrier that uses a map held in memory as a storage +// medium for propagated key-value pairs. +type MapCarrier map[string]string + +// Compile time check that MapCarrier implements the TextMapCarrier. +var _ TextMapCarrier = MapCarrier{} + +// Get returns the value associated with the passed key. +func (c MapCarrier) Get(key string) string { + return c[key] +} + +// Set stores the key-value pair. +func (c MapCarrier) Set(key, value string) { + c[key] = value +} + +// Keys lists the keys stored in this carrier. +func (c MapCarrier) Keys() []string { + keys := make([]string, 0, len(c)) + for k := range c { + keys = append(keys, k) + } + return keys +} + // HeaderCarrier adapts http.Header to satisfy the TextMapCarrier interface. type HeaderCarrier http.Header diff --git a/propagation/propagation_test.go b/propagation/propagation_test.go index 12d93cb9cf4..488d6551d5b 100644 --- a/propagation/propagation_test.go +++ b/propagation/propagation_test.go @@ -16,9 +16,12 @@ package propagation_test import ( "context" + "sort" "strings" "testing" + "github.com/stretchr/testify/assert" + "go.opentelemetry.io/otel/propagation" ) @@ -102,3 +105,33 @@ func TestCompositeTextMapPropagatorExtract(t *testing.T) { t.Errorf("invalid extract order: %s", got) } } + +func TestMapCarrierGet(t *testing.T) { + carrier := propagation.MapCarrier{ + "foo": "bar", + "baz": "qux", + } + + assert.Equal(t, carrier.Get("foo"), "bar") + assert.Equal(t, carrier.Get("baz"), "qux") +} + +func TestMapCarrierSet(t *testing.T) { + carrier := make(propagation.MapCarrier) + carrier.Set("foo", "bar") + carrier.Set("baz", "qux") + + assert.Equal(t, carrier["foo"], "bar") + assert.Equal(t, carrier["baz"], "qux") +} + +func TestMapCarrierKeys(t *testing.T) { + carrier := propagation.MapCarrier{ + "foo": "bar", + "baz": "qux", + } + + keys := carrier.Keys() + sort.Strings(keys) + assert.Equal(t, []string{"baz", "foo"}, keys) +}