server_and_client.cc 897 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // server_and_client.cc
  3. //
  4. // Copyright (c) 2024 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <iostream>
  8. #include <string>
  9. #include <string>
  10. #include <httplib.h>
  11. using namespace httplib;
  12. const char *HOST = "localhost";
  13. const int PORT = 1234;
  14. const std::string JSON_DATA = R"({"hello": "world"})";
  15. int main(void) {
  16. Server svr;
  17. svr.Post("/api", [&](const Request & /*req*/, Response &res) {
  18. res.set_content("Hello World!", "text/plain");
  19. });
  20. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21. auto se = detail::scope_exit([&] {
  22. svr.stop();
  23. thread.join();
  24. });
  25. svr.wait_until_ready();
  26. Client cli(HOST, PORT);
  27. auto res =
  28. cli.Post("/api", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  29. "application/json", [](uint64_t, uint64_t) { return true; });
  30. if (res) {
  31. std::cout << res->body << std::endl;
  32. }
  33. }