I use the Simple-Web-Server library to create a simple web service for translating XML to JSON and vice versa. In turn, it uses several boost libraries , as well as boost :: coroutine among them. To convert XML ↔ JSON, I use the boost :: property_tree library for an intermediate view. Here is the code:
#include <iostream>
#include <sstream>
#include <server_http.hpp>
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
using namespace std;
using namespace boost::property_tree;
using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
int main()
{
HttpServer server(8080, 1);
server.resource["^/json_to_xml$"]["POST"] = [](auto& response, auto request) {
try
{
ptree pt;
read_json(request->content, pt);
ostringstream json, xml;
write_json(json, pt);
clog << "JSON request content:" << endl << json.str() << endl;
write_xml(xml, pt, xml_writer_make_settings<ptree::key_type>(' ', 1u));
clog << "XML response content:" << endl << xml.str() << endl;
response << "HTTP/1.1 200 OK\r\nContent-Length: " << xml.str().length() << "\r\n\r\n" << xml.str();
}
catch(const exception& e)
{
cerr << "Error:" << endl << e.what() << endl;
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
}
};
server.resource["^/xml_to_json$"]["POST"] = [](auto& response, auto request) {
try
{
ptree pt;
read_xml(request->content, pt, xml_parser::trim_whitespace | xml_parser::no_comments);
ostringstream xml, json;
write_xml(xml, pt, xml_writer_make_settings<ptree::key_type>(' ', 1u));
clog << "XML request content:" << endl << xml.str() << endl;
write_json(json, pt);
clog << "JSON response content: " << endl << json.str() << endl;
response << "HTTP/1.1 200 OK\r\nContent-Length: " << json.str().length() << "\r\n\r\n" << json.str();
}
catch(const exception& e)
{
cerr << "Error:" << endl << e.what() << endl;
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
}
};
server.start();
return 0;
}
JSON XML , . boost:: property_tree XML , . - . GDB backtrace. , , - Valgrind.
boost - 1.58.0, 1.61.0. 1.4.2 Simple-Web-Server.