api: keep the error contract JSON even on encoder failure
writeJSON's last-resort branch (json.Marshal failing, a programmer
error: unsupported type or cyclic data) previously fell back to
http.Error, which answers text/plain and was the one corner where the
API broke its own {"error": ...} contract. It now writes a
hand-written constant JSON literal: still strictly simpler than the
encoder that just failed (the reason writeError, which is built ON
writeJSON, cannot be used there: it would be circular), but contract
consistent. Tested by forcing the branch with a channel payload,
which json.Marshal cannot encode.
This commit is contained in:
parent
b49d92ec50
commit
2feb6ea5a3
2 changed files with 29 additions and 1 deletions
|
|
@ -22,6 +22,29 @@ func serve(t *testing.T, method, path string, body []byte) *httptest.ResponseRec
|
|||
return recorder
|
||||
}
|
||||
|
||||
func TestWriteJSONEncodingFailureStaysJSON(t *testing.T) {
|
||||
// Channels cannot be marshaled, forcing the otherwise unreachable
|
||||
// last-resort branch. Even there the error contract must stay JSON.
|
||||
recorder := httptest.NewRecorder()
|
||||
writeJSON(recorder, http.StatusOK, make(chan int))
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d, want %d", recorder.Code, http.StatusInternalServerError)
|
||||
}
|
||||
if got := recorder.Header().Get("Content-Type"); got != "application/json" {
|
||||
t.Errorf("Content-Type = %q, want application/json", got)
|
||||
}
|
||||
var response struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("fallback body is not JSON: %v (body: %s)", err, recorder.Body)
|
||||
}
|
||||
if response.Error == "" {
|
||||
t.Error("fallback body has an empty error field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultConfigEndpoint(t *testing.T) {
|
||||
recorder := serve(t, http.MethodGet, "/api/config/default", nil)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue