From 48ac21df559bb9539dc0249c7f0d3a9099f159ec Mon Sep 17 00:00:00 2001 From: Jake Kelly Date: Wed, 14 Jul 2021 14:16:31 +0200 Subject: [PATCH] feat(matchers): Support custom MIME types (#88) --- matchers.go | 9 +++++++-- matchers_test.go | 27 +++++++++++++++++++++++++++ request.go | 2 +- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/matchers.go b/matchers.go index 52ae5f0..658c9a6 100644 --- a/matchers.go +++ b/matchers.go @@ -148,7 +148,7 @@ func MatchBody(req *http.Request, ereq *Request) (bool, error) { } // Only can match certain MIME body types - if !supportedType(req) { + if !supportedType(req, ereq) { return false, nil } @@ -214,12 +214,17 @@ func MatchBody(req *http.Request, ereq *Request) (bool, error) { return false, nil } -func supportedType(req *http.Request) bool { +func supportedType(req *http.Request, ereq *Request) bool { mime := req.Header.Get("Content-Type") if mime == "" { return true } + mimeToMatch := ereq.Header.Get("Content-Type") + if mimeToMatch != "" { + return mime == mimeToMatch + } + for _, kind := range BodyTypes { if match, _ := regexp.MatchString(kind, mime); match { return true diff --git a/matchers_test.go b/matchers_test.go index 855e40c..56aaa01 100644 --- a/matchers_test.go +++ b/matchers_test.go @@ -222,3 +222,30 @@ func TestMatchBody(t *testing.T) { st.Expect(t, matches, test.matches) } } + +func TestMatchBody_MatchType(t *testing.T) { + body := `{"foo":"bar"}` + cases := []struct { + body string + requestContentType string + customBodyType string + matches bool + }{ + {body, "application/vnd.apiname.v1+json", "foobar", false}, + {body, "application/vnd.apiname.v1+json", "application/vnd.apiname.v1+json", true}, + {body, "application/json", "foobar", false}, + {body, "application/json", "", true}, + {"", "", "", true}, + } + + for _, test := range cases { + req := &http.Request{ + Header: http.Header{"Content-Type": []string{test.requestContentType}}, + Body: createReadCloser([]byte(test.body)), + } + ereq := NewRequest().BodyString(test.body).MatchType(test.customBodyType) + matches, err := MatchBody(req, ereq) + st.Expect(t, err, nil) + st.Expect(t, matches, test.matches) + } +} diff --git a/request.go b/request.go index 4259169..5702417 100644 --- a/request.go +++ b/request.go @@ -176,7 +176,7 @@ func (r *Request) XML(data interface{}) *Request { } // MatchType defines the request Content-Type MIME header field. -// Supports type alias. E.g: json, xml, form, text... +// Supports custom MIME types and type aliases. E.g: json, xml, form, text... func (r *Request) MatchType(kind string) *Request { mime := BodyTypeAliases[kind] if mime != "" {