server.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. //
  2. // sample.cc
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #include <httplib.h>
  8. #include <cstdio>
  9. #ifdef _WIN32
  10. #define snprintf sprintf_s
  11. #endif
  12. std::string dump_headers(const httplib::MultiMap& headers)
  13. {
  14. std::string s;
  15. char buf[BUFSIZ];
  16. for (auto it = headers.begin(); it != headers.end(); ++it) {
  17. const auto& x = *it;
  18. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  19. s += buf;
  20. }
  21. return s;
  22. }
  23. std::string log(const httplib::Connection& c)
  24. {
  25. const auto& req = c.request;
  26. const auto& res = c.response;
  27. std::string s;
  28. char buf[BUFSIZ];
  29. s += "================================\n";
  30. snprintf(buf, sizeof(buf), "%s %s", req.method.c_str(), req.url.c_str());
  31. s += buf;
  32. std::string query;
  33. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  34. const auto& x = *it;
  35. snprintf(buf, sizeof(buf), "%c%s=%s",
  36. (it == req.params.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str());
  37. query += buf;
  38. }
  39. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  40. s += buf;
  41. s += dump_headers(req.headers);
  42. s += "--------------------------------\n";
  43. snprintf(buf, sizeof(buf), "%d\n", res.status);
  44. s += buf;
  45. s += dump_headers(res.headers);
  46. if (!res.body.empty()) {
  47. s += res.body;
  48. }
  49. s += "\n";
  50. return s;
  51. }
  52. int main(void)
  53. {
  54. using namespace httplib;
  55. Server svr("localhost", 8080);
  56. svr.get("/", [=](Connection& c) {
  57. c.response.set_redirect("/hi");
  58. });
  59. svr.get("/hi", [](Connection& c) {
  60. c.response.set_content("Hello World!", "text/plain");
  61. });
  62. svr.get("/dump", [](Connection& c) {
  63. c.response.set_content(dump_headers(c.request.headers), "text/plain");
  64. });
  65. svr.get("/stop", [&](Connection& c) {
  66. svr.stop();
  67. });
  68. svr.set_error_handler([](Connection& c) {
  69. const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
  70. char buf[BUFSIZ];
  71. snprintf(buf, sizeof(buf), fmt, c.response.status);
  72. c.response.set_content(buf, "text/html");
  73. });
  74. svr.set_logger([](const Connection& c) {
  75. printf("%s", log(c).c_str());
  76. });
  77. svr.run();
  78. return 0;
  79. }
  80. // vim: et ts=4 sw=4 cin cino={1s ff=unix