server.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. using namespace httplib;
  10. std::string dump_headers(const MultiMap& headers)
  11. {
  12. std::string s;
  13. char buf[BUFSIZ];
  14. for (auto it = headers.begin(); it != headers.end(); ++it) {
  15. const auto& x = *it;
  16. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  17. s += buf;
  18. }
  19. return s;
  20. }
  21. std::string log(const Request& req, const Response& res)
  22. {
  23. std::string s;
  24. char buf[BUFSIZ];
  25. s += "================================\n";
  26. snprintf(buf, sizeof(buf), "%s %s", req.method.c_str(), req.url.c_str());
  27. s += buf;
  28. std::string query;
  29. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  30. const auto& x = *it;
  31. snprintf(buf, sizeof(buf), "%c%s=%s",
  32. (it == req.params.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str());
  33. query += buf;
  34. }
  35. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  36. s += buf;
  37. s += dump_headers(req.headers);
  38. s += "--------------------------------\n";
  39. snprintf(buf, sizeof(buf), "%d\n", res.status);
  40. s += buf;
  41. s += dump_headers(res.headers);
  42. if (!res.body.empty()) {
  43. s += res.body;
  44. }
  45. s += "\n";
  46. return s;
  47. }
  48. int main(void)
  49. {
  50. Server svr;
  51. svr.get("/", [=](const auto& req, auto& res) {
  52. res.set_redirect("/hi");
  53. });
  54. svr.get("/hi", [](const auto& req, auto& res) {
  55. res.set_content("Hello World!", "text/plain");
  56. });
  57. svr.get("/dump", [](const auto& req, auto& res) {
  58. res.set_content(dump_headers(req.headers), "text/plain");
  59. });
  60. svr.get("/stop", [&](const auto& req, auto& res) {
  61. svr.stop();
  62. });
  63. svr.set_error_handler([](const auto& req, auto& res) {
  64. const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
  65. char buf[BUFSIZ];
  66. snprintf(buf, sizeof(buf), fmt, res.status);
  67. res.set_content(buf, "text/html");
  68. });
  69. svr.set_logger([](const auto& req, const auto& res) {
  70. printf("%s", log(req, res).c_str());
  71. });
  72. svr.listen("localhost", 8080);
  73. return 0;
  74. }
  75. // vim: et ts=4 sw=4 cin cino={1s ff=unix