From 1f83821f78c23f576101bf6ed887ceaa3322c9ce Mon Sep 17 00:00:00 2001 From: Macy Date: Sat, 19 Oct 2024 11:07:47 -0700 Subject: [PATCH] fix: also consider Accept header in addition to Content-Type when making decisions on media type --- mock/mock_engine.go | 7 +++++++ mock/mock_engine_test.go | 15 ++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/mock/mock_engine.go b/mock/mock_engine.go index d8dc702..a254d96 100644 --- a/mock/mock_engine.go +++ b/mock/mock_engine.go @@ -160,7 +160,14 @@ func (rme *ResponseMockEngine) extractMediaTypeHeader(request *http.Request) str if mediaTypeSting == "" { mediaTypeSting = contentType // anything? } + if mediaTypeSting == "" { + // Check the Accept header for a content type + contentType = request.Header.Get("Accept") + mediaTypeSting, _, _ = helpers.ExtractContentType(contentType) + } + + if (mediaTypeSting == "") { mediaTypeSting = "application/json" // default } diff --git a/mock/mock_engine_test.go b/mock/mock_engine_test.go index 917bde2..43cc02d 100644 --- a/mock/mock_engine_test.go +++ b/mock/mock_engine_test.go @@ -1100,17 +1100,26 @@ components: assert.Equal(t, "robocop", decoded["name"]) assert.Equal(t, "perhaps the best cyberpunk movie ever made.", decoded["description"]) - // Now see if html will work + // Now see if html will work with preferred header for second html example request, _ = http.NewRequest(http.MethodGet, "https://api.pb33f.io/test", nil) - request.Header.Set(helpers.Preferred, "happyHtmlDays") + request.Header.Set(helpers.Preferred, "robocopInHtml") request.Header.Set("Content-Type", "text/html") b, status, err = me.GenerateResponse(request) assert.NoError(t, err) assert.Equal(t, 200, status) - assert.Equal(t, "

Happy Days", string(b[:])) + assert.Equal(t, "

Robo cop", string(b[:])) + + // Now see if html will work w/ Accept header and no preferred + request, _ = http.NewRequest(http.MethodGet, "https://api.pb33f.io/test", nil) + request.Header.Set("Accept", "text/html") + + b, status, err = me.GenerateResponse(request) + assert.NoError(t, err) + assert.Equal(t, 200, status) + assert.Equal(t, "

Happy Days", string(b[:])) } // https://github.com/pb33f/wiretap/issues/83