HttpHandler.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #ifndef HTTP_HANDLER_H_
  2. #define HTTP_HANDLER_H_
  3. #include "HttpSession.h"
  4. #include "HttpService.h"
  5. #include "FileCache.h"
  6. #include "hloop.h"
  7. #define HTTP_KEEPALIVE_TIMEOUT 75 // s
  8. static inline void on_keepalive_timeout(htimer_t* timer) {
  9. hio_t* io = (hio_t*)hevent_userdata(timer);
  10. hio_close(io);
  11. }
  12. class HttpHandler {
  13. public:
  14. // peeraddr
  15. char ip[64];
  16. int port;
  17. // for handle_request
  18. HttpService* service;
  19. FileCache* files;
  20. HttpSession* session;
  21. HttpRequest req;
  22. HttpResponse res;
  23. file_cache_t* fc;
  24. // for keepalive
  25. hio_t* io;
  26. htimer_t* keepalive_timer;
  27. HttpHandler() {
  28. service = NULL;
  29. files = NULL;
  30. session = NULL;
  31. fc = NULL;
  32. io = NULL;
  33. keepalive_timer = NULL;
  34. }
  35. ~HttpHandler() {
  36. if (keepalive_timer) {
  37. htimer_del(keepalive_timer);
  38. keepalive_timer = NULL;
  39. }
  40. }
  41. // @workflow: preprocessor -> api -> web -> postprocessor
  42. // @result: HttpRequest -> HttpResponse/file_cache_t
  43. int HandleRequest();
  44. void Reset() {
  45. fc = NULL;
  46. req.Reset();
  47. res.Reset();
  48. }
  49. void KeepAlive() {
  50. if (keepalive_timer == NULL) {
  51. keepalive_timer = htimer_add(hevent_loop(io), on_keepalive_timeout, HTTP_KEEPALIVE_TIMEOUT*1000, 1);
  52. hevent_set_userdata(keepalive_timer, io);
  53. }
  54. else {
  55. htimer_reset(keepalive_timer);
  56. }
  57. }
  58. };
  59. #endif // HTTP_HANDLER_H_