From 3a6caa2800f8c54a548a6ec370c9339e61044541 Mon Sep 17 00:00:00 2001
From: "Alexander A. Klimov"
Date: Mon, 1 Apr 2019 12:43:38 +0200
Subject: [PATCH] Respect Accept:application/json where possible
---
lib/remote/httpserverconnection.cpp | 34 ++++++++++++++++++++++++-----
1 file changed, 28 insertions(+), 6 deletions(-)
diff --git a/lib/remote/httpserverconnection.cpp b/lib/remote/httpserverconnection.cpp
index d041e23ac..af5169952 100644
--- a/lib/remote/httpserverconnection.cpp
+++ b/lib/remote/httpserverconnection.cpp
@@ -102,6 +102,8 @@ bool EnsureValidHeaders(
{
namespace http = boost::beast::http;
+ bool httpError = true;
+
try {
try {
http::async_read_header(stream, buf, parser, yc);
@@ -115,6 +117,8 @@ bool EnsureValidHeaders(
throw std::invalid_argument(ex.what());
}
+ httpError = false;
+
switch (parser.get().version()) {
case 10:
case 11:
@@ -124,9 +128,18 @@ bool EnsureValidHeaders(
}
} catch (const std::invalid_argument& ex) {
response.result(http::status::bad_request);
- response.set(http::field::content_type, "text/html");
- response.body() = String("Bad Request
") + ex.what() + "
";
- response.set(http::field::content_length, response.body().size());
+
+ if (!httpError && parser.get()[http::field::accept] == "application/json") {
+ HttpUtility::SendJsonBody(response, nullptr, new Dictionary({
+ { "error", 400 },
+ { "status", String("Bad Request: ") + ex.what() }
+ }));
+ } else {
+ response.set(http::field::content_type, "text/html");
+ response.body() = String("Bad Request
") + ex.what() + "
";
+ response.set(http::field::content_length, response.body().size());
+ }
+
response.set(http::field::connection, "close");
http::async_write(stream, response, yc);
@@ -333,9 +346,18 @@ bool EnsureValidBody(
*/
response.result(http::status::bad_request);
- response.set(http::field::content_type, "text/html");
- response.body() = String("Bad Request
") + ex.what() + "
";
- response.set(http::field::content_length, response.body().size());
+
+ if (parser.get()[http::field::accept] == "application/json") {
+ HttpUtility::SendJsonBody(response, nullptr, new Dictionary({
+ { "error", 400 },
+ { "status", String("Bad Request: ") + ex.what() }
+ }));
+ } else {
+ response.set(http::field::content_type, "text/html");
+ response.body() = String("Bad Request
") + ex.what() + "
";
+ response.set(http::field::content_length, response.body().size());
+ }
+
response.set(http::field::connection, "close");
http::async_write(stream, response, yc);