Skip to content

Commit

Permalink
Merge branch 'klauspost-Add_RequestExcludeHeaderFunc'
Browse files Browse the repository at this point in the history
  • Loading branch information
seborama committed Oct 25, 2018
2 parents 8832eee + 1df4573 commit ab1528d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
27 changes: 27 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,33 @@ func RequestDeleteHeaderKeys(keys ...string) RequestFilter {
}
}

// RequestExcludeHeaderFunc is a hook function that is used to filter the Header.
//
// Typically this can be used to remove / amend undesirable custom headers from the request.
//
// For instance, if your application sends requests with a timestamp held in a custom header,
// you likely want to exclude it from the comparison to ensure that the request headers are
// considered a match with those saved on the cassette's track.
//
// Parameters:
// - parameter 1 - Name of header key in the Request
//
// Return value:
// true - exclude header key from comparison
// false - retain header key for comparison
//
// Deprecated - This function will be removed on or after April 25th 2019
func RequestExcludeHeaderFunc(fn func(key string) bool) RequestFilter {
return func(req Request) Request {
for key := range req.Header {
if fn(key) {
req.Header.Del(key)
}
}
return req
}
}

// OnMethod will return a new filter that will only apply 'r'
// if the method of the request matches.
// Original filter is unmodified.
Expand Down
29 changes: 29 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,35 @@ func TestRequestDeleteHeaderKeys(t *testing.T) {
}
}

func TestRequestExcludeHeaderFunc(t *testing.T) {
req := requestTestBase()
req.Header.Add("another-header", "yeah")
header1, header2 := textproto.CanonicalMIMEHeaderKey("a-header"), textproto.CanonicalMIMEHeaderKey("another-header")

// We expect both headers to be checked.
want := map[string]struct{}{header1:{}, header2: {}}
r := RequestExcludeHeaderFunc(func(key string) bool {
_, ok := want[key]
if !ok {
t.Errorf("got unexpected key %q", key)
}
// Delete so we check we only get key once.
delete(want, key)
// Delete 'a-header'
return header1 == key
})
req = r(req)
if len(want) > 0 {
t.Errorf("header was not checked: %v", want)
}
if len(req.Header) != 1 {
t.Fatalf("unexpected header count, want one: %v", req.Header)
}
if req.Header.Get("another-header") != "yeah" {
t.Errorf("unexpected header value: %s", req.Header.Get("another-header"))
}
}

func TestRequestFilters_Add(t *testing.T) {
var f RequestFilters
f1, ok1 := mustCallRequestFilterOnce(t)
Expand Down

0 comments on commit ab1528d

Please sign in to comment.