1
0

HttpHandler.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #ifndef HV_HTTP_HANDLER_H_
  2. #define HV_HTTP_HANDLER_H_
  3. #include "HttpService.h"
  4. #include "HttpParser.h"
  5. #include "FileCache.h"
  6. #include "WebSocketServer.h"
  7. #include "WebSocketParser.h"
  8. class HttpHandler {
  9. public:
  10. enum ProtocolType {
  11. UNKNOWN,
  12. HTTP_V1,
  13. HTTP_V2,
  14. WEBSOCKET,
  15. } protocol;
  16. enum State {
  17. WANT_RECV,
  18. HANDLE_BEGIN,
  19. HANDLE_CONTINUE,
  20. HANDLE_END,
  21. WANT_SEND,
  22. SEND_HEADER,
  23. SEND_BODY,
  24. SEND_DONE,
  25. } state;
  26. // peeraddr
  27. bool ssl;
  28. char ip[64];
  29. int port;
  30. // for http
  31. HttpService *service;
  32. HttpRequestPtr req;
  33. HttpResponsePtr resp;
  34. HttpResponseWriterPtr writer;
  35. HttpParserPtr parser;
  36. HttpContextPtr ctx;
  37. http_handler* api_handler;
  38. // for sendfile
  39. FileCache *files;
  40. file_cache_ptr fc; // cache small file
  41. struct LargeFile : public HFile {
  42. HBuf buf;
  43. uint64_t timer;
  44. } *file; // for large file
  45. // for GetSendData
  46. std::string header;
  47. // std::string body;
  48. // for websocket
  49. WebSocketService* ws_service;
  50. WebSocketChannelPtr ws_channel;
  51. WebSocketParserPtr ws_parser;
  52. uint64_t last_send_ping_time;
  53. uint64_t last_recv_pong_time;
  54. HttpHandler();
  55. ~HttpHandler();
  56. bool Init(int http_version = 1, hio_t* io = NULL);
  57. void Reset();
  58. int FeedRecvData(const char* data, size_t len);
  59. // @workflow: preprocessor -> api -> web -> postprocessor
  60. // @result: HttpRequest -> HttpResponse/file_cache_t
  61. int HandleHttpRequest();
  62. int GetSendData(char** data, size_t* len);
  63. // HTTP2
  64. bool SwitchHTTP2();
  65. // websocket
  66. bool SwitchWebSocket(hio_t* io = NULL);
  67. void WebSocketOnOpen() {
  68. ws_channel->status = hv::SocketChannel::CONNECTED;
  69. if (ws_service && ws_service->onopen) {
  70. ws_service->onopen(ws_channel, req);
  71. }
  72. }
  73. void WebSocketOnClose() {
  74. ws_channel->status = hv::SocketChannel::DISCONNECTED;
  75. if (ws_service && ws_service->onclose) {
  76. ws_service->onclose(ws_channel);
  77. }
  78. }
  79. private:
  80. int openFile(const char* filepath);
  81. int sendFile();
  82. void closeFile();
  83. bool isFileOpened();
  84. const HttpContextPtr& getHttpContext();
  85. void onHeadersComplete();
  86. int defaultRequestHandler();
  87. int defaultStaticHandler();
  88. int defaultLargeFileHandler();
  89. int defaultErrorHandler();
  90. int customHttpHandler(const http_handler& handler);
  91. int invokeHttpHandler(const http_handler* handler);
  92. };
  93. #endif // HV_HTTP_HANDLER_H_