1
0

HttpService.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 "hexport.h"
  9. #include "HttpMessage.h"
  10. #define DEFAULT_BASE_URL "/v1/api"
  11. #define DEFAULT_DOCUMENT_ROOT "/var/www/html"
  12. #define DEFAULT_HOME_PAGE "index.html"
  13. /*
  14. * @param[in] req: parsed structured http request
  15. * @param[out] res: structured http response
  16. * @return 0: handle continue
  17. * http_status_code: handle done
  18. */
  19. typedef int (*http_api_handler)(HttpRequest* req, HttpResponse* res);
  20. struct http_method_handler {
  21. http_method method;
  22. http_api_handler handler;
  23. http_method_handler(http_method m = HTTP_POST, http_api_handler h = NULL) {
  24. method = m;
  25. handler = h;
  26. }
  27. };
  28. // method => http_api_handler
  29. typedef std::list<http_method_handler> http_method_handlers;
  30. // path => http_method_handlers
  31. typedef std::map<std::string, std::shared_ptr<http_method_handlers>> http_api_handlers;
  32. struct HV_EXPORT HttpService {
  33. // preprocessor -> api -> web -> postprocessor
  34. http_api_handler preprocessor;
  35. http_api_handler postprocessor;
  36. // api service
  37. std::string base_url;
  38. http_api_handlers api_handlers;
  39. // web service
  40. std::string document_root;
  41. std::string home_page;
  42. std::string error_page;
  43. std::string index_of;
  44. HttpService() {
  45. preprocessor = NULL;
  46. postprocessor = NULL;
  47. base_url = DEFAULT_BASE_URL;
  48. document_root = DEFAULT_DOCUMENT_ROOT;
  49. home_page = DEFAULT_HOME_PAGE;
  50. }
  51. void AddApi(const char* path, http_method method, http_api_handler handler);
  52. // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED
  53. int GetApi(const char* url, http_method method, http_api_handler* handler);
  54. // RESTful API /:field/ => req->query_params["field"]
  55. int GetApi(HttpRequest* req, http_api_handler* handler);
  56. };
  57. #endif // HTTP_SERVICE_H_