simplesvr.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. if (argc > 1 && string("--help") == argv[1]) {
  48. cout << "usage: simplesvr [PORT] [DIR]" << endl;
  49. return 1;
  50. }
  51. Server svr;
  52. svr.set_error_handler([](const auto& req, auto& res) {
  53. const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
  54. char buf[BUFSIZ];
  55. snprintf(buf, sizeof(buf), fmt, res.status);
  56. res.set_content(buf, "text/html");
  57. });
  58. svr.set_logger([](const auto& req, const auto& res) {
  59. cout << log(req, res);
  60. });
  61. auto port = 80;
  62. if (argc > 1) {
  63. port = atoi(argv[1]);
  64. }
  65. auto base_dir = "./";
  66. if (argc > 2) {
  67. base_dir = argv[2];
  68. }
  69. svr.set_base_dir(base_dir);
  70. cout << "The server started at port " << port << "...";
  71. svr.listen("localhost", port);
  72. return 0;
  73. }
  74. // vim: et ts=4 sw=4 cin cino={1s ff=unix