server-http.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #pragma once
  2. #include <atomic>
  3. #include <functional>
  4. #include <map>
  5. #include <string>
  6. #include <thread>
  7. struct common_params;
  8. // generator-like API for HTTP response generation
  9. // this object response with one of the 2 modes:
  10. // 1) normal response: `data` contains the full response body
  11. // 2) streaming response: each call to next(output) generates the next chunk
  12. // when next(output) returns false, no more data after the current chunk
  13. // note: some chunks can be empty, in which case no data is sent for that chunk
  14. struct server_http_res {
  15. std::string content_type = "application/json; charset=utf-8";
  16. int status = 200;
  17. std::string data;
  18. std::map<std::string, std::string> headers;
  19. // TODO: move this to a virtual function once we have proper polymorphism support
  20. std::function<bool(std::string &)> next = nullptr;
  21. bool is_stream() const {
  22. return next != nullptr;
  23. }
  24. virtual ~server_http_res() = default;
  25. };
  26. // unique pointer, used by set_chunked_content_provider
  27. // httplib requires the stream provider to be stored in heap
  28. using server_http_res_ptr = std::unique_ptr<server_http_res>;
  29. struct server_http_req {
  30. std::map<std::string, std::string> params; // path_params + query_params
  31. std::map<std::string, std::string> headers; // reserved for future use
  32. std::string path; // reserved for future use
  33. std::string body;
  34. const std::function<bool()> & should_stop;
  35. std::string get_param(const std::string & key, const std::string & def = "") const {
  36. auto it = params.find(key);
  37. if (it != params.end()) {
  38. return it->second;
  39. }
  40. return def;
  41. }
  42. };
  43. struct server_http_context {
  44. class Impl;
  45. std::unique_ptr<Impl> pimpl;
  46. std::thread thread; // server thread
  47. std::atomic<bool> is_ready = false;
  48. std::string path_prefix;
  49. std::string hostname;
  50. int port;
  51. server_http_context();
  52. ~server_http_context();
  53. bool init(const common_params & params);
  54. bool start();
  55. void stop() const;
  56. // note: the handler should never throw exceptions
  57. using handler_t = std::function<server_http_res_ptr(const server_http_req & req)>;
  58. void get(const std::string & path, const handler_t & handler) const;
  59. void post(const std::string & path, const handler_t & handler) const;
  60. // for debugging
  61. std::string listening_address;
  62. };