Skip to content

Commit

Permalink
feat(v2): add BuildHeaders to header
Browse files Browse the repository at this point in the history
  • Loading branch information
quartzmo committed Jun 22, 2023
1 parent 8620d81 commit 184ca25
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions v2/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ package gax
import (
"bytes"
"context"
"net/http"
"runtime"
"strings"
"unicode"
Expand Down Expand Up @@ -135,3 +136,15 @@ func InsertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
}
return metadata.NewOutgoingContext(ctx, out)
}

// BuildHeaders is for use by the Google Cloud Libraries only.
//
// BuildHeaders extracts metadata from the outgoing context, joins it with any
// other given metadata, and converts them into a http.Header.
func BuildHeaders(ctx context.Context, mds ...metadata.MD) http.Header {
if cmd, ok := metadata.FromOutgoingContext(ctx); ok {
mds = append(mds, cmd)
}
md := metadata.Join(mds...)
return http.Header(md)
}
17 changes: 17 additions & 0 deletions v2/header_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ package gax

import (
"context"
"net/http"
"reflect"
"testing"

Expand Down Expand Up @@ -109,3 +110,19 @@ func TestInsertMetadata(t *testing.T) {
t.Errorf("InsertMetadata(ctx, %q) = %q, want %q", mds, got, want)
}
}

func TestBuildHeaders(t *testing.T) {
existingMd := metadata.Pairs("key_1", "val_1")
ctx := metadata.NewOutgoingContext(context.Background(), existingMd)
mds := []metadata.MD{
metadata.Pairs("key_2", "val_21"),
metadata.Pairs("key_2", "val_22"),
}

got := BuildHeaders(ctx, mds...)

want := http.Header{"key_1": []string{"val_1"}, "key_2": []string{"val_21", "val_22"}}
if !reflect.DeepEqual(got, want) {
t.Errorf("BuildHeaders(ctx, %q) = %q, want %q", mds, got, want)
}
}

0 comments on commit 184ca25

Please sign in to comment.