Skip to content

Commit df4b5a8

Browse files
committed
Extend the content type matching to include application/foo+json format
1 parent 896443d commit df4b5a8

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

cmd/cmd.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"fmt"
66
"net/http"
7+
"regexp"
78
"strings"
89

910
"io"
@@ -23,6 +24,8 @@ var (
2324
Out io.Writer
2425
// Err is used to write errors.
2526
Err io.Writer
27+
// jsonContentTypeRe is used to match Content-Type which contains JSON.
28+
jsonContentTypeRe = regexp.MustCompile(`^application/([[:alpha:]]+\+)?json$`)
2629
)
2730

2831
const msgWelcomePleaseConfigure = `
@@ -77,7 +80,7 @@ func validateUserConfig(cfg *viper.Viper) error {
7780
// decodedAPIError decodes and returns the error message from the API response.
7881
// If the message is blank, it returns a fallback message with the status code.
7982
func decodedAPIError(resp *http.Response) error {
80-
if contentType := resp.Header.Get("Content-Type"); contentType != "application/json" {
83+
if contentType := resp.Header.Get("Content-Type"); !jsonContentTypeRe.MatchString(contentType) {
8184
return fmt.Errorf(
8285
"expected response with Content-Type \"application/json\" but got status %q with Content-Type %q",
8386
resp.Status,

cmd/cmd_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,19 @@ func TestDecodeErrorResponse(t *testing.T) {
156156
response: errorResponse("application/json", `{"error": {"message": "message"}}`),
157157
wantMessage: "message",
158158
},
159+
{
160+
response: errorResponse("application/problem+json", `{"error": {"message": "new json format"}}`),
161+
wantMessage: "new json format",
162+
},
159163
{
160164
response: errorResponse("application/json", `{"error": {}}`),
161165
wantMessage: "unexpected API response: 418",
162166
},
163167
}
164-
for _, tc := range testCases {
168+
tc := testCases[0]
169+
got := decodedAPIError(tc.response)
170+
assert.Equal(t, tc.wantMessage, got.Error())
171+
for _, tc = range testCases {
165172
got := decodedAPIError(tc.response)
166173
assert.Equal(t, tc.wantMessage, got.Error())
167174
}

0 commit comments

Comments
 (0)