format response body as unicode text and hexadecimal v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Fri, 25 Mar 2022 00:39:11 +0100
branchv_0
changeset 22 1bbfcb95db82
parent 21 1a4174f4693a
child 23 33f8162a4971
format response body as unicode text and hexadecimal
src/HTTPHandler.h
--- a/src/HTTPHandler.h	Thu Mar 24 02:19:39 2022 +0100
+++ b/src/HTTPHandler.h	Fri Mar 25 00:39:11 2022 +0100
@@ -23,6 +23,7 @@
 #include <regex>
 #include <locale>
 #include <stdexcept>
+#include <iomanip>
 
 #include <curl/curl.h>
 #include <uuid/uuid.h>
@@ -129,6 +130,23 @@
 		return convertor.from_bytes(buffer);
 	}
 
+	relpipe::common::type::StringX bodyToText(const std::string& body, bool* validEncoding = nullptr) {
+		try {
+			if (validEncoding) *validEncoding = true;
+			return convertor.from_bytes(body);
+		} catch (...) {
+			if (validEncoding) *validEncoding = false;
+			return L"";
+		}
+	}
+
+	relpipe::common::type::StringX bodyToHex(const std::string& body) {
+		std::stringstream hex;
+		hex << std::hex << std::setfill('0') << std::hex;
+		for (size_t i = 0, size = body.size(); i < size; i++) hex << std::setw(2) << (0xff & body[i]);
+		return convertor.from_bytes(hex.str());
+	}
+
 public:
 
 	HTTPHandler(shared_ptr<relpipe::writer::RelationalWriter> relationalWriter, Configuration configuration) : relationalWriter(relationalWriter), configuration(configuration) {
@@ -148,10 +166,10 @@
 			// TODO: analyze header attributes
 		} else if (currentRelationName == L"request") {
 			relationalWriter->startRelation(L"response",{
-				// TODO: body in hexadecimal/binary format
 				{L"request", relpipe::writer::TypeId::STRING},
 				{L"url", relpipe::writer::TypeId::STRING},
-				{L"body", relpipe::writer::TypeId::STRING},
+				{L"text", relpipe::writer::TypeId::STRING},
+				{L"data", relpipe::writer::TypeId::STRING},
 				{L"code", relpipe::writer::TypeId::INTEGER},
 			}, true);
 		}
@@ -224,7 +242,8 @@
 
 			relationalWriter->writeAttribute(requestId);
 			relationalWriter->writeAttribute(convertor.from_bytes(request.url));
-			relationalWriter->writeAttribute(convertor.from_bytes(body));
+			relationalWriter->writeAttribute(bodyToText(body));
+			relationalWriter->writeAttribute(bodyToHex(body)); // TODO: return as an octet-string (when supported) instead of hexadecimal
 			relationalWriter->writeAttribute(&responseCode, typeid (responseCode));
 
 			request = HTTPClient::Request();