main.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // main.cc
  3. //
  4. // Copyright (c) 2024 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <chrono>
  8. #include <ctime>
  9. #include <format>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <sstream>
  13. #include <httplib.h>
  14. constexpr auto error_html = R"(<html>
  15. <head><title>{} {}</title></head>
  16. <body>
  17. <center><h1>404 Not Found</h1></center>
  18. <hr><center>cpp-httplib/{}</center>
  19. </body>
  20. </html>
  21. )";
  22. std::string time_local() {
  23. auto p = std::chrono::system_clock::now();
  24. auto t = std::chrono::system_clock::to_time_t(p);
  25. std::stringstream ss;
  26. ss << std::put_time(std::localtime(&t), "%d/%b/%Y:%H:%M:%S %z");
  27. return ss.str();
  28. }
  29. std::string log(auto &req, auto &res) {
  30. auto remote_user = "-"; // TODO:
  31. auto request = std::format("{} {} {}", req.method, req.path, req.version);
  32. auto body_bytes_sent = res.get_header_value("Content-Length");
  33. auto http_referer = "-"; // TODO:
  34. auto http_user_agent = req.get_header_value("User-Agent", "-");
  35. // NOTE: From NGINX defualt access log format
  36. // log_format combined '$remote_addr - $remote_user [$time_local] '
  37. // '"$request" $status $body_bytes_sent '
  38. // '"$http_referer" "$http_user_agent"';
  39. return std::format(R"({} - {} [{}] "{}" {} {} "{}" "{}")", req.remote_addr,
  40. remote_user, time_local(), request, res.status,
  41. body_bytes_sent, http_referer, http_user_agent);
  42. }
  43. int main(int argc, const char **argv) {
  44. auto base_dir = "./html";
  45. auto host = "0.0.0.0";
  46. auto port = 80;
  47. httplib::Server svr;
  48. svr.set_error_handler([](auto & /*req*/, auto &res) {
  49. auto body =
  50. std::format(error_html, res.status, httplib::status_message(res.status),
  51. CPPHTTPLIB_VERSION);
  52. res.set_content(body, "text/html");
  53. });
  54. svr.set_logger(
  55. [](auto &req, auto &res) { std::cout << log(req, res) << std::endl; });
  56. svr.set_mount_point("/", base_dir);
  57. std::cout << std::format("Serving HTTP on {0} port {1} ...", host, port)
  58. << std::endl;
  59. auto ret = svr.listen(host, port);
  60. return ret ? 0 : 1;
  61. }