Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

metadata: add ValueFromIncomingContext to more efficiently retrieve a single value #5596

Merged
merged 6 commits into from
Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,20 +197,19 @@ func FromIncomingContext(ctx context.Context) (MD, bool) {

// ValueFromIncomingContext returns value from the incoming metadata if exists.
//
// This is intended for using as fast access to context value with string constant.
// ValueFromIncomingContext returns the metadata value corresponding to the metadata
horpto marked this conversation as resolved.
Show resolved Hide resolved
// key from the incoming metadata if it exists.
func ValueFromIncomingContext(ctx context.Context, key string) []string {
md, ok := ctx.Value(mdIncomingKey{}).(MD)
if !ok {
return nil
}
// fastpath

if v, ok := md[key]; ok {
res := make([]string, len(v))
horpto marked this conversation as resolved.
Show resolved Hide resolved
copy(res, v)
return res
}

// slowpath
key = strings.ToLower(key)
horpto marked this conversation as resolved.
Show resolved Hide resolved
for k, v := range md {
// We need to manually convert all keys to lower case, because MD is a
Expand Down
39 changes: 25 additions & 14 deletions metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,20 +206,31 @@ func (s) TestValueFromIncomingContext(t *testing.T) {
)
ctx := NewIncomingContext(context.Background(), md)

var v []string
v = ValueFromIncomingContext(ctx, "X-My-Header-1")
if !reflect.DeepEqual(v, []string{"42"}) {
t.Errorf("value from context is %v", v)
}

v = ValueFromIncomingContext(ctx, "x-my-header-1")
if !reflect.DeepEqual(v, []string{"42"}) {
t.Errorf("value from context is %v", v)
}

v = ValueFromIncomingContext(ctx, "x-my-header-2")
if !reflect.DeepEqual(v, []string{"43-1", "43-2"}) {
t.Errorf("value from context is %v", v)
for _, test := range []struct {
key string
want []string
}{
{
key: "X-My-Header-1",
want: []string{"42"},
},
{
key: "x-my-header-1",
want: []string{"42"},
},
{
key: "x-my-header-2",
want: []string{"43-1", "43-2"},
},
{
key: "x-unknown",
want: nil,
},
} {
v := ValueFromIncomingContext(ctx, test.key)
if !reflect.DeepEqual(v, test.want) {
t.Errorf("value of metadata is %v, want %v", v, test.want)
}
}
}

Expand Down