crow::black_magic::const_str doesn't seem to be able to be used with const std::string types
Author: cmpunchesCreated Jan 13, 2018Updated Jan 5, 2024
These classes don't seem to be able to play well with built-ins which impacts abstractions during wrapping:
#include "crow/amalgamate/crow_all.h"
struct route
{
// the relative URL used
std::string URL;
// the HTTP method to use
std::string method;
// a function pointer expected to process the route entry
void (*route_handler)(crow::SimpleApp &, route &);
};
// -------
void index_handler( crow::SimpleApp &app, route route_specs )
{
const std::string url = (crow::black_magic::const_str) route_specs.URL;
std::string method = (crow::black_magic::const_str) route_specs.method;
// TODO need to figure out how this ""_method operator actually works to interpolate route_specs.method
CROW_ROUTE(app, url).methods("GET"_method)
( [] () {
// expects (route)index
return "API is online.";
});
}
void add_two_numbers( crow::SimpleApp &app, route route_specs )
{
std::string url = (crow::black_magic::const_str) route_specs.URL;
std::string method = (crow::black_magic::const_str) route_specs.method;
// TODO need to figure out how this ""_method operator actually works to interpolate route_specs.method
CROW_ROUTE(app, url).methods("POST"_method)
( [] (const crow::request& req) {
auto x = crow::json::load(req.body);
auto y = crow::json::dump(x);
if (!x)
return crow::response(400);
int sum = x["a"].i()+x["b"].i();
std::ostringstream os;
os << sum;
return crow::response{os.str()};
} );
}
// -------
class RestAPI
{
public:
RestAPI( crow::SimpleApp &app, std::list<route> shape );
};
RestAPI::RestAPI( crow::SimpleApp &app, std::list<route> shape ) {
// executes 3rd member of all members of (APIShape)shape with its parent struct as its first argument?
// for entry in shape run entry.handler
std::list<route>::iterator it;
for (it = shape.begin(); it != shape.end(); ++it )
{
it->route_handler( app, *it );
}
}
// ------
int main(int argc, char *argv[])
{
crow::SimpleApp app;
std::list<route> apiShape;
route index = { "/", "GET", &index_handler };
route add_nums = { "/add_two_numbers/<int>/<int>", "GET", &add_two_numbers };
apiShape.push_back( index );
apiShape.push_back( add_nums );
RestAPI restAPI( app, apiShape );
/*
CROW_ROUTE(app, "/").methods("GET"_method)
( [] () {
return "Hello world!";
});
CROW_ROUTE(app,"/hello/<int>/<int>").methods("GET"_method)
( [] (int count, int count2) {
if (count > 100)
return crow::response(400);
std::ostringstream os;
os << count << " bottles of beer!" << "and " << count2;
return crow::response(os.str());
} );
CROW_ROUTE(app, "/add_json").methods("POST"_method)
( [] (const crow::request& req) {
auto x = crow::json::load(req.body);
auto y = crow::json::dump(x);
if (!x)
return crow::response(400);
int sum = x["a"].i()+x["b"].i();
std::ostringstream os;
// os << sum;
os << y;
return crow::response{os.str()};
} );
*/
app.port(18080).run();
}Source: ipkn/crow