sample.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // sample.cc
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #include <httpsvrkit.h>
  8. #include <cstdio>
  9. using namespace httpsvrkit;
  10. std::string dump_request(Context& cxt)
  11. {
  12. std::string s;
  13. char buf[BUFSIZ];
  14. s += "================================\n";
  15. sprintf(buf, "Method: %s\n", cxt.request.method.c_str());
  16. s += buf;
  17. sprintf(buf, "URL: %s\n", cxt.request.url.c_str());
  18. s += buf;
  19. std::string query;
  20. for (auto it = cxt.request.query.begin(); it != cxt.request.query.end(); ++it) {
  21. const auto& x = *it;
  22. sprintf(buf, "(%s:%s)", x.first.c_str(), x.second.c_str());
  23. query += buf;
  24. }
  25. sprintf(buf, "QUERY: %s\n", query.c_str());
  26. s += buf;
  27. //for (const auto& x : cxt.request.headers) {
  28. for (auto it = cxt.request.headers.begin(); it != cxt.request.headers.end(); ++it) {
  29. const auto& x = *it;
  30. sprintf(buf, "%s: %s\n", x.first.c_str(), x.second.c_str());
  31. s += buf;
  32. }
  33. s += "================================\n";
  34. return s;
  35. }
  36. int main(void)
  37. {
  38. if (true) {
  39. // DSL style
  40. HTTP_SERVER("localhost", 1234) {
  41. GET("/", {
  42. res.set_redirect("/home");
  43. });
  44. GET("/home", {
  45. res.set_content(dump_request(cxt));
  46. });
  47. }
  48. } else {
  49. // Regular style
  50. Server svr("localhost", 1234);
  51. svr.get("/", [](Context& cxt) {
  52. cxt.response.set_redirect("/home");
  53. });
  54. svr.get("/home", [](Context& cxt) {
  55. cxt.response.set_content(dump_request(cxt));
  56. });
  57. svr.post("/item", [](Context& cxt) {
  58. cxt.response.set_content(dump_request(cxt));
  59. });
  60. svr.get("/item/([^/]+)", [](Context& cxt) {
  61. cxt.response.set_content(dump_request(cxt));
  62. });
  63. svr.run();
  64. }
  65. }
  66. // vim: et ts=4 sw=4 cin cino={1s ff=unix