2
0

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