HttpService.h 1.9 KB

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