simplesvr.cc 1.9 KB

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