main.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <httplib.h>
  2. #include <iostream>
  3. #include "sqlitedb.h"
  4. namespace App {
  5. constexpr auto DefaultPort = 8888;
  6. constexpr auto DefaultHost = "0.0.0.0";
  7. constexpr auto ContentType = "application/json";
  8. static httplib::Server *srv = nullptr;
  9. } // namespace App
  10. void signalHandler(int signum)
  11. {
  12. std::cout << "\n\nInterrupt signal (" << signum << ") received.\n" << std::endl;
  13. if (App::srv) {
  14. App::srv->stop();
  15. delete App::srv;
  16. }
  17. exit(signum);
  18. }
  19. int main(int argc, char *argv[])
  20. {
  21. std::signal(SIGINT, signalHandler);
  22. App::srv = new httplib::Server();
  23. SqliteDb db("beer.db");
  24. auto read_table = [&db](const httplib::Request& req, httplib::Response& res) {
  25. auto table = req.path_params.at("table");
  26. std::vector< SqliteDb::Param> params;
  27. for (const auto& [param, value] : req.params)
  28. {
  29. params.push_back({ param, value });
  30. }
  31. res.set_content("Table: " + db.readTable( table, params ), "text/plain");
  32. };
  33. App::srv->Get("/table/:table", read_table);
  34. auto host = argc > 1 ? argv[1] : App::DefaultHost;
  35. auto port = argc > 2 ? atoi(argv[2]) : App::DefaultPort;
  36. std::cout << "Listen on " << host << ":" << port << std::endl;
  37. App::srv->listen(host, port);
  38. return 0;
  39. }