server.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. #include <signal.h>
  10. template<typename Fn> void signal(int sig, Fn fn)
  11. {
  12. static std::function<void ()> signal_handler_;
  13. struct SignalHandler { static void fn(int sig) { signal_handler_(); } };
  14. signal_handler_ = fn;
  15. signal(sig, SignalHandler::fn);
  16. }
  17. std::string log(const httplib::Connection& c)
  18. {
  19. const auto& req = c.request;
  20. const auto& res = c.response;
  21. std::string s;
  22. char buf[BUFSIZ];
  23. s += "================================\n";
  24. snprintf(buf, sizeof(buf), "%s %s", req.method.c_str(), req.url.c_str());
  25. s += buf;
  26. std::string query;
  27. for (auto it = req.query.begin(); it != req.query.end(); ++it) {
  28. const auto& x = *it;
  29. snprintf(buf, sizeof(buf), "%c%s=%s",
  30. (it == req.query.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str());
  31. query += buf;
  32. }
  33. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  34. s += buf;
  35. s += httplib::dump_headers(req.headers);
  36. s += "--------------------------------\n";
  37. snprintf(buf, sizeof(buf), "%d\n", res.status);
  38. s += buf;
  39. s += httplib::dump_headers(res.headers);
  40. if (!res.body.empty()) {
  41. s += res.body;
  42. }
  43. s += "\n";
  44. return s;
  45. }
  46. int main(void)
  47. {
  48. using namespace httplib;
  49. const char* hi = "/hi";
  50. Server svr("localhost", 1234);
  51. svr.get("/", [=](Connection& c) {
  52. c.response.set_redirect(hi);
  53. });
  54. svr.get("/hi", [](Connection& c) {
  55. c.response.set_content("Hello World!");
  56. });
  57. svr.get("/dump", [](Connection& c) {
  58. c.response.set_content(log(c));
  59. });
  60. svr.set_logger([](const Connection& c) {
  61. printf("%s", log(c).c_str());
  62. });
  63. signal(SIGINT, [&]() { svr.stop(); });
  64. svr.run();
  65. return 0;
  66. }
  67. // vim: et ts=4 sw=4 cin cino={1s ff=unix