HttpService.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #ifndef HTTP_SERVICE_H_
  2. #define HTTP_SERVICE_H_
  3. #include <string.h>
  4. #include <string>
  5. #include <map>
  6. #include <list>
  7. #include <memory>
  8. #include "HttpMessage.h"
  9. #define DEFAULT_BASE_URL "/v1/api"
  10. #define DEFAULT_DOCUMENT_ROOT "/var/www/html"
  11. #define DEFAULT_HOME_PAGE "index.html"
  12. #define HANDLE_CONTINUE 0
  13. #define HANDLE_DONE 1
  14. typedef int (*http_api_handler)(HttpRequest* req, HttpResponse* res);
  15. struct http_method_handler {
  16. http_method method;
  17. http_api_handler handler;
  18. http_method_handler(http_method m = HTTP_POST, http_api_handler h = NULL) {
  19. method = m;
  20. handler = h;
  21. }
  22. };
  23. // method => http_api_handler
  24. typedef std::list<http_method_handler> http_method_handlers;
  25. // path => http_method_handlers
  26. typedef std::map<std::string, std::shared_ptr<http_method_handlers>> http_api_handlers;
  27. struct HttpService {
  28. // preprocessor -> api -> web -> postprocessor
  29. http_api_handler preprocessor;
  30. http_api_handler postprocessor;
  31. // api service
  32. std::string base_url;
  33. http_api_handlers api_handlers;
  34. // web service
  35. std::string document_root;
  36. std::string home_page;
  37. std::string error_page;
  38. std::string index_of;
  39. HttpService() {
  40. preprocessor = NULL;
  41. postprocessor = NULL;
  42. base_url = DEFAULT_BASE_URL;
  43. document_root = DEFAULT_DOCUMENT_ROOT;
  44. home_page = DEFAULT_HOME_PAGE;
  45. }
  46. void AddApi(const char* path, http_method method, http_api_handler handler);
  47. // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED
  48. int GetApi(const char* url, http_method method, http_api_handler* handler);
  49. // RESTful API /:field/ => req->query_params["field"]
  50. int GetApi(HttpRequest* req, http_api_handler* handler);
  51. };
  52. #endif // HTTP_SERVICE_H_