simplesvr.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. //
  2. // simplesvr.cc
  3. //
  4. // Copyright (c) 2013 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #include <httplib.h>
  8. #include <cstdio>
  9. #include <iostream>
  10. #define SERVER_CERT_FILE "./cert.pem"
  11. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  12. using namespace httplib;
  13. using namespace std;
  14. string dump_headers(const MultiMap& headers)
  15. {
  16. string s;
  17. char buf[BUFSIZ];
  18. for (const auto& x: headers) {
  19. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  20. s += buf;
  21. }
  22. return s;
  23. }
  24. string log(const Request& req, const Response& res)
  25. {
  26. string s;
  27. char buf[BUFSIZ];
  28. s += "================================\n";
  29. snprintf(buf, sizeof(buf), "%s %s", req.method.c_str(), req.url.c_str());
  30. s += buf;
  31. string query;
  32. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  33. const auto& x = *it;
  34. snprintf(buf, sizeof(buf), "%c%s=%s",
  35. (it == req.params.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str());
  36. query += buf;
  37. }
  38. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  39. s += buf;
  40. s += dump_headers(req.headers);
  41. s += "--------------------------------\n";
  42. snprintf(buf, sizeof(buf), "%d\n", res.status);
  43. s += buf;
  44. s += dump_headers(res.headers);
  45. return s;
  46. }
  47. int main(int argc, const char** argv)
  48. {
  49. if (argc > 1 && string("--help") == argv[1]) {
  50. cout << "usage: simplesvr [PORT] [DIR]" << endl;
  51. return 1;
  52. }
  53. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  54. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  55. #else
  56. Server svr;
  57. #endif
  58. svr.set_error_handler([](const auto& req, auto& res) {
  59. const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
  60. char buf[BUFSIZ];
  61. snprintf(buf, sizeof(buf), fmt, res.status);
  62. res.set_content(buf, "text/html");
  63. });
  64. svr.set_logger([](const auto& req, const auto& res) {
  65. cout << log(req, res);
  66. });
  67. auto port = 80;
  68. if (argc > 1) {
  69. port = atoi(argv[1]);
  70. }
  71. auto base_dir = "./";
  72. if (argc > 2) {
  73. base_dir = argv[2];
  74. }
  75. svr.set_base_dir(base_dir);
  76. cout << "The server started at port " << port << "...";
  77. svr.listen("localhost", port);
  78. return 0;
  79. }
  80. // vim: et ts=4 sw=4 cin cino={1s ff=unix