Crow:黑魔法 基于Rule的绑定参数调用绑定function/lambda

Crow有一个很有意思的实现,就是绑定url时的参数可以跟处理lambda的类型自动匹配

CROW_ROUTE(app, "/hello/")
([](int count) {
    if (count > 100)
        return crow::response(400);
    std::ostringstream os;
    os << count << " bottles of beer!";
    return crow::response(os.str());
});

CROW_ROUTE(app, "/add//")
([](crow::response& res, int a, int b) {
    std::ostringstream os;
    os << a + b;
    res.write(os.str());
    res.end();
});

CROW_ROUTE(app, "/add_json")
.methods("POST"_method)([](const crow::request& req) {
  auto x = crow::json::load(req.body);
  if (!x)
      return crow::response(400);
  int sum = x["a"].i() + x["b"].i();
  std::ostringstream os;
  os << sum;
  return crow::response{os.str()};
});

可以看到lambda可以有int参数,可以有res,也可以有偶req,这些参数都可以被动态的绑定到CROW_ROUTE上,

你可能感兴趣的:(C/C++,c++)