fixed a bug in JSON validation

This commit is contained in:
Нурлыгаянова Екатерина
2026-10-29 14:34:10 +03:00
parent 1503b5db81
commit 8bb0350f6d
2 changed files with 6 additions and 1 deletions
+1 -1
View File
@@ -71,7 +71,7 @@ func decodeJSON(body io.Reader, dst any) error {
if err := dec.Decode(dst); err != nil {
return &validate.Error{Field: "body", Reason: jsonErrorReason(err)}
}
if dec.More() {
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"}
}
return checkExactKeys(data, dst)
+5
View File
@@ -21,6 +21,10 @@ func TestValidation_InvalidJSON(t *testing.T) {
[]byte(`{"text": 123,}`),
[]byte(``),
[]byte(`{"text": "ok"}{"text":"bonus"}`),
[]byte(`{"text": "ok"}}`),
[]byte(`{"text": "ok"}]`),
[]byte(`{"text": "ok"} }`),
[]byte(`{"text": "ok"} x`),
[]byte("{\"text\":\"\xff\xfe bad utf8\"}"),
}
for _, payload := range bad {
@@ -104,6 +108,7 @@ func TestValidation_ErrorMessages(t *testing.T) {
{http.MethodPost, "/api/v1/users", "", ``, "body: empty body"},
{http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}}`, "body: unexpected data after JSON object"},
{http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}",
"body: invalid UTF-8"},
{http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`,