example.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #include "crow.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. struct ExampleMiddleware
  10. {
  11. std::string message;
  12. ExampleMiddleware()
  13. {
  14. message = "foo";
  15. }
  16. void setMessage(std::string newMsg)
  17. {
  18. message = newMsg;
  19. }
  20. struct context
  21. {
  22. };
  23. void before_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
  24. {
  25. CROW_LOG_DEBUG << " - MESSAGE: " << message;
  26. }
  27. void after_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
  28. {
  29. // no-op
  30. }
  31. };
  32. int main()
  33. {
  34. crow::App<ExampleMiddleware> app;
  35. app.get_middleware<ExampleMiddleware>().setMessage("hello");
  36. CROW_ROUTE(app, "/")
  37. .name("hello")
  38. ([]{
  39. return "Hello World!";
  40. });
  41. CROW_ROUTE(app, "/about")
  42. ([](){
  43. return "About Crow example.";
  44. });
  45. // a request to /path should be forwarded to /path/
  46. CROW_ROUTE(app, "/path/")
  47. ([](){
  48. return "Trailing slash test case..";
  49. });
  50. // simple json response
  51. // To see it in action enter {ip}:18080/json
  52. CROW_ROUTE(app, "/json")
  53. ([]{
  54. crow::json::wvalue x;
  55. x["message"] = "Hello, World!";
  56. return x;
  57. });
  58. // To see it in action enter {ip}:18080/hello/{integer_between -2^32 and 100} and you should receive
  59. // {integer_between -2^31 and 100} bottles of beer!
  60. CROW_ROUTE(app,"/hello/<int>")
  61. ([](int count){
  62. if (count > 100)
  63. return crow::response(400);
  64. std::ostringstream os;
  65. os << count << " bottles of beer!";
  66. return crow::response(os.str());
  67. });
  68. // To see it in action submit {ip}:18080/add/1/2 and you should receive 3 (exciting, isn't it)
  69. CROW_ROUTE(app,"/add/<int>/<int>")
  70. ([](const crow::request& /*req*/, crow::response& res, int a, int b){
  71. std::ostringstream os;
  72. os << a+b;
  73. res.write(os.str());
  74. res.end();
  75. });
  76. // Compile error with message "Handler type is mismatched with URL paramters"
  77. //CROW_ROUTE(app,"/another/<int>")
  78. //([](int a, int b){
  79. //return crow::response(500);
  80. //});
  81. // more json example
  82. // To see it in action, I recommend to use the Postman Chrome extension:
  83. // * Set the address to {ip}:18080/add_json
  84. // * Set the method to post
  85. // * Select 'raw' and then JSON
  86. // * Add {"a": 1, "b": 1}
  87. // * Send and you should receive 2
  88. // A simpler way for json example:
  89. // * curl -d '{"a":1,"b":2}' {ip}:18080/add_json
  90. CROW_ROUTE(app, "/add_json")
  91. .methods("POST"_method)
  92. ([](const crow::request& req){
  93. auto x = crow::json::load(req.body);
  94. if (!x)
  95. return crow::response(400);
  96. int sum = x["a"].i()+x["b"].i();
  97. std::ostringstream os;
  98. os << sum;
  99. return crow::response{os.str()};
  100. });
  101. // Example of a request taking URL parameters
  102. // If you want to activate all the functions just query
  103. // {ip}:18080/params?foo='blabla'&pew=32&count[]=a&count[]=b
  104. CROW_ROUTE(app, "/params")
  105. ([](const crow::request& req){
  106. std::ostringstream os;
  107. // To get a simple string from the url params
  108. // To see it in action /params?foo='blabla'
  109. os << "Params: " << req.url_params << "\n\n";
  110. os << "The key 'foo' was " << (req.url_params.get("foo") == nullptr ? "not " : "") << "found.\n";
  111. // To get a double from the request
  112. // To see in action submit something like '/params?pew=42'
  113. if(req.url_params.get("pew") != nullptr) {
  114. double countD = boost::lexical_cast<double>(req.url_params.get("pew"));
  115. os << "The value of 'pew' is " << countD << '\n';
  116. }
  117. // To get a list from the request
  118. // You have to submit something like '/params?count[]=a&count[]=b' to have a list with two values (a and b)
  119. auto count = req.url_params.get_list("count");
  120. os << "The key 'count' contains " << count.size() << " value(s).\n";
  121. for(const auto& countVal : count) {
  122. os << " - " << countVal << '\n';
  123. }
  124. // To get a dictionary from the request
  125. // You have to submit something like '/params?mydict[a]=b&mydict[abcd]=42' to have a list of pairs ((a, b) and (abcd, 42))
  126. auto mydict = req.url_params.get_dict("mydict");
  127. os << "The key 'dict' contains " << mydict.size() << " value(s).\n";
  128. for(const auto& mydictVal : mydict) {
  129. os << " - " << mydictVal.first << " -> " << mydictVal.second << '\n';
  130. }
  131. return crow::response{os.str()};
  132. });
  133. CROW_ROUTE(app, "/large")
  134. ([]{
  135. return std::string(512*1024, ' ');
  136. });
  137. // enables all log
  138. app.loglevel(crow::LogLevel::DEBUG);
  139. //crow::logger::setHandler(std::make_shared<ExampleLogHandler>());
  140. app.port(18080)
  141. .multithreaded()
  142. .run();
  143. }