ipkn / crow

Crow is very fast and easy to use C++ micro web framework (inspired by Python Flask)
BSD 3-Clause "New" or "Revised" License
7.47k stars 888 forks source link

How do you abstract the CROW_ROUTE directive to a function? #281

Open cmpunches opened 6 years ago

cmpunches commented 6 years ago

something like:

void alt_crow_route(crow::SimpleApp &app, crow::black_magic::const_str url, const char * method, funcptr hander)
{
    app.route<crow::black_magic::get_parameter_tag(url)>( (crow::black_magic::const_str) url ).methods(method->_method).handler(handler);
}

?? I just can't see it. Also the crow::black_magic::const_str compatibility issue in #278 is an obstacle for this issue as well. There doesn't seem to be a way to convert between the two. Please advise. If there is a better place to ask this please let me know.

d-led commented 6 years ago

does route_dynamic help? tests/unittest.cpp#L1146

szulyoben commented 6 years ago

crow::black_magic::const_str is using constexpr under the hood, so app.route\<crow::black_magic::get_parameter_tag(url)>(url) requires compile time information of the route, which is probably not what you want. Instead you can use route_dynamic as @d-led mentioned. Here is a dummy example:


constexpr char foo[] = "/foo";
CROW_ROUTE(app, foo)
([]{
    return "Route has to be available at compile time!";
});

srand (time(NULL));
int num = rand() % 10 + 1;
std::string dyn_route_str = "/" + std::to_string(num);
char dyn_route[64];
strncpy(dyn_route, dyn_route_str.c_str(), sizeof(dyn_route));
dyn_route[sizeof(dyn_route) - 1] = 0;

app.route_dynamic(dyn_route)
([]{
  return "This gives a bit more flexibility on defining route at run time!";
});`