example_with_all.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "../amalgamate/crow_all.h"
  2. #include <sstream>
  3. class ExampleLogHandler : public crow::ILogHandler {
  4. public:
  5. void log(std::string /*message*/, crow::LogLevel /*level*/) override {
  6. // cerr << "ExampleLogHandler -> " << message;
  7. }
  8. };
  9. int main()
  10. {
  11. crow::SimpleApp app;
  12. CROW_ROUTE(app, "/")
  13. .name("hello")
  14. ([]{
  15. return "Hello World!";
  16. });
  17. CROW_ROUTE(app, "/about")
  18. ([](){
  19. return "About Crow example.";
  20. });
  21. // simple json response
  22. CROW_ROUTE(app, "/json")
  23. ([]{
  24. crow::json::wvalue x;
  25. x["message"] = "Hello, World!";
  26. return x;
  27. });
  28. CROW_ROUTE(app,"/hello/<int>")
  29. ([](int count){
  30. if (count > 100)
  31. return crow::response(400);
  32. std::ostringstream os;
  33. os << count << " bottles of beer!";
  34. return crow::response(os.str());
  35. });
  36. CROW_ROUTE(app,"/add/<int>/<int>")
  37. ([](const crow::request& /*req*/, crow::response& res, int a, int b){
  38. std::ostringstream os;
  39. os << a+b;
  40. res.write(os.str());
  41. res.end();
  42. });
  43. // Compile error with message "Handler type is mismatched with URL paramters"
  44. //CROW_ROUTE(app,"/another/<int>")
  45. //([](int a, int b){
  46. //return crow::response(500);
  47. //});
  48. // more json example
  49. CROW_ROUTE(app, "/add_json")
  50. ([](const crow::request& req){
  51. auto x = crow::json::load(req.body);
  52. if (!x)
  53. return crow::response(400);
  54. int sum = x["a"].i()+x["b"].i();
  55. std::ostringstream os;
  56. os << sum;
  57. return crow::response{os.str()};
  58. });
  59. CROW_ROUTE(app, "/params")
  60. ([](const crow::request& req){
  61. std::ostringstream os;
  62. os << "Params: " << req.url_params << "\n\n";
  63. os << "The key 'foo' was " << (req.url_params.get("foo") == nullptr ? "not " : "") << "found.\n";
  64. if(req.url_params.get("pew") != nullptr) {
  65. double countD = boost::lexical_cast<double>(req.url_params.get("pew"));
  66. os << "The value of 'pew' is " << countD << '\n';
  67. }
  68. auto count = req.url_params.get_list("count");
  69. os << "The key 'count' contains " << count.size() << " value(s).\n";
  70. for(const auto& countVal : count) {
  71. os << " - " << countVal << '\n';
  72. }
  73. return crow::response{os.str()};
  74. });
  75. // ignore all log
  76. crow::logger::setLogLevel(crow::LogLevel::Debug);
  77. //crow::logger::setHandler(std::make_shared<ExampleLogHandler>());
  78. app.port(18080)
  79. .multithreaded()
  80. .run();
  81. }