server_and_client.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // server_and_client.cc
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <httplib.h>
  8. #include <iostream>
  9. #include <string>
  10. using namespace httplib;
  11. std::string dump_headers(const Headers &headers) {
  12. std::string s;
  13. char buf[BUFSIZ];
  14. for (auto it = headers.begin(); it != headers.end(); ++it) {
  15. const auto &x = *it;
  16. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  17. s += buf;
  18. }
  19. return s;
  20. }
  21. void logger(const Request &req, const Response &res) {
  22. std::string s;
  23. char buf[BUFSIZ];
  24. s += "================================\n";
  25. snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(),
  26. req.version.c_str(), req.path.c_str());
  27. s += buf;
  28. std::string query;
  29. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  30. const auto &x = *it;
  31. snprintf(buf, sizeof(buf), "%c%s=%s",
  32. (it == req.params.begin()) ? '?' : '&', x.first.c_str(),
  33. 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 %s\n", res.status, res.version.c_str());
  41. s += buf;
  42. s += dump_headers(res.headers);
  43. s += "\n";
  44. if (!res.body.empty()) { s += res.body; }
  45. s += "\n";
  46. std::cout << s;
  47. }
  48. int main(void) {
  49. // Server
  50. Server svr;
  51. svr.set_logger(logger);
  52. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  53. res.set_content("POST", "text/plain");
  54. });
  55. auto th = std::thread([&]() { svr.listen("localhost", 8080); });
  56. auto se = detail::scope_exit([&] {
  57. svr.stop();
  58. th.join();
  59. });
  60. svr.wait_until_ready();
  61. // Client
  62. Client cli{"localhost", 8080};
  63. std::string body = R"({"hello": "world"})";
  64. auto res = cli.Post("/post", body, "application/json");
  65. std::cout << "--------------------------------" << std::endl;
  66. std::cout << to_string(res.error()) << std::endl;
  67. }