Skip to content

Commit 0de0abe

Browse files
committed
Assert response content type
1 parent c165b5b commit 0de0abe

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

nuts/util.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ func ParseResponse[T any](err error, httpResponse *http.Response, fn func(rsp *h
2727
detail := "Response data:\n----------------\n" + strings.TrimSpace(string(responseData)) + "\n----------------"
2828
return nil, fmt.Errorf("non-OK status code (status=%s, url=%s)\n%s", httpResponse.Status, httpResponse.Request.URL, detail)
2929
}
30+
if !strings.Contains(httpResponse.Header.Get("Content-Type"), "application/json") {
31+
return nil, fmt.Errorf("unexpected response content type: %s", httpResponse.Header.Get("Content-Type"))
32+
}
3033
result, err := fn(httpResponse)
3134
if err != nil {
3235
return nil, fmt.Errorf("failed to parse response: %w", err)

nuts/util_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ func Test_ParseResponse(t *testing.T) {
2020
StatusCode: 200,
2121
Status: "200 OK",
2222
Body: io.NopCloser(strings.NewReader("http-test-response")),
23+
Header: http.Header{"Content-Type": []string{"application/json;charset=utf-8"}},
2324
Request: httptest.NewRequest(http.MethodGet, "http://example.com", nil),
2425
}
2526
}
@@ -28,6 +29,7 @@ func Test_ParseResponse(t *testing.T) {
2829
StatusCode: 404,
2930
Status: "404 Not Found",
3031
Body: io.NopCloser(strings.NewReader("http-test-response")),
32+
Header: http.Header{"Content-Type": []string{"application/json;charset=utf-8"}},
3133
Request: httptest.NewRequest(http.MethodGet, "http://example.com", nil),
3234
}
3335
}
@@ -50,4 +52,14 @@ func Test_ParseResponse(t *testing.T) {
5052
_, err := ParseResponse(nil, nokResponse(), fn)
5153
require.EqualError(t, err, "non-OK status code (status=404 Not Found, url=http://example.com)\nResponse data:\n----------------\nhttp-test-response\n----------------")
5254
})
55+
t.Run("unexpected content type", func(t *testing.T) {
56+
_, err := ParseResponse(nil, &http.Response{
57+
StatusCode: 200,
58+
Status: "200 OK",
59+
Body: io.NopCloser(strings.NewReader("http-test-response")),
60+
Request: httptest.NewRequest(http.MethodGet, "http://example.com", nil),
61+
Header: http.Header{"Content-Type": []string{"text/plain"}},
62+
}, fn)
63+
require.EqualError(t, err, "unexpected response content type: text/plain")
64+
})
5365
}

0 commit comments

Comments
 (0)