Skip to content

Commit

Permalink
fix: also consider Accept header in addition to Content-Type when mak…
Browse files Browse the repository at this point in the history
…ing decisions on media type
  • Loading branch information
macyabbey authored and daveshanley committed Nov 1, 2024
1 parent 9c88a63 commit 1f83821
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 7 additions & 0 deletions mock/mock_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
15 changes: 12 additions & 3 deletions mock/mock_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<!DOCTYPE html><html lang=\"en\"><body><h1>Happy Days</h1</body></html>", string(b[:]))
assert.Equal(t, "<!DOCTYPE html><html lang=\"en\"><body><h1>Robo cop</h1</body></html>", 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, "<!DOCTYPE html><html lang=\"en\"><body><h1>Happy Days</h1</body></html>", string(b[:]))
}

// https://github.com/pb33f/wiretap/issues/83
Expand Down

0 comments on commit 1f83821

Please sign in to comment.