server.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. inline void error_handler(httplib::Connection& c)
  47. {
  48. char buf[BUFSIZ];
  49. snprintf(buf, sizeof(buf), "Error Status: %d\r\n", c.response.status);
  50. c.response.set_content(buf);
  51. }
  52. int main(void)
  53. {
  54. using namespace httplib;
  55. const char* hi = "/hi";
  56. Server svr("localhost", 8080);
  57. svr.get("/", [=](Connection& c) {
  58. c.response.set_redirect(hi);
  59. });
  60. svr.get("/hi", [](Connection& c) {
  61. c.response.set_content("Hello World!");
  62. });
  63. svr.get("/dump", [](Connection& c) {
  64. c.response.set_content(httplib::dump_headers(c.request.headers));
  65. });
  66. svr.error(error_handler);
  67. svr.set_logger([](const Connection& c) {
  68. printf("%s", log(c).c_str());
  69. });
  70. signal(SIGINT, [&]() { svr.stop(); });
  71. svr.run();
  72. return 0;
  73. }
  74. // vim: et ts=4 sw=4 cin cino={1s ff=unix