1
0

HttpResponseWriter.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #ifndef HV_HTTP_RESPONSE_WRITER_H_
  2. #define HV_HTTP_RESPONSE_WRITER_H_
  3. #include "Channel.h"
  4. #include "HttpMessage.h"
  5. namespace hv {
  6. class HV_EXPORT HttpResponseWriter : public SocketChannel {
  7. public:
  8. HttpResponsePtr response;
  9. enum State {
  10. SEND_BEGIN = 0,
  11. SEND_HEADER,
  12. SEND_BODY,
  13. SEND_CHUNKED,
  14. SEND_CHUNKED_END,
  15. SEND_END,
  16. } state: 8, end: 8;
  17. HttpResponseWriter(hio_t* io, const HttpResponsePtr& resp)
  18. : SocketChannel(io)
  19. , response(resp)
  20. , state(SEND_BEGIN)
  21. , end(SEND_BEGIN)
  22. {}
  23. ~HttpResponseWriter() {}
  24. // Begin -> End
  25. // Begin -> WriteResponse -> End
  26. // Begin -> WriteStatus -> WriteHeader -> WriteBody -> End
  27. // Begin -> EndHeaders("Content-Type", "text/event-stream") -> write -> write -> ... -> close
  28. // Begin -> EndHeaders("Content-Length", content_length) -> WriteBody -> WriteBody -> ... -> End
  29. // Begin -> EndHeaders("Transfer-Encoding", "chunked") -> WriteChunked -> WriteChunked -> ... -> End
  30. int Begin() {
  31. state = end = SEND_BEGIN;
  32. return 0;
  33. }
  34. int WriteStatus(http_status status_codes) {
  35. response->status_code = status_codes;
  36. return 0;
  37. }
  38. int WriteHeader(const char* key, const char* value) {
  39. response->SetHeader(key, value);
  40. return 0;
  41. }
  42. template<typename T>
  43. int WriteHeader(const char* key, T num) {
  44. response->SetHeader(key, hv::to_string(num));
  45. return 0;
  46. }
  47. int WriteCookie(const HttpCookie& cookie) {
  48. response->cookies.push_back(cookie);
  49. return 0;
  50. }
  51. int EndHeaders(const char* key = NULL, const char* value = NULL);
  52. template<typename T>
  53. int EndHeaders(const char* key, T num) {
  54. std::string value = hv::to_string(num);
  55. return EndHeaders(key, value.c_str());
  56. }
  57. int WriteChunked(const char* buf, int len = -1);
  58. int WriteChunked(const std::string& str) {
  59. return WriteChunked(str.c_str(), str.size());
  60. }
  61. int EndChunked() {
  62. return WriteChunked(NULL, 0);
  63. }
  64. int WriteBody(const char* buf, int len = -1);
  65. int WriteBody(const std::string& str) {
  66. return WriteBody(str.c_str(), str.size());
  67. }
  68. int WriteResponse(HttpResponse* resp);
  69. int SSEvent(const std::string& data, const char* event = "message");
  70. int End(const char* buf = NULL, int len = -1);
  71. int End(const std::string& str) {
  72. return End(str.c_str(), str.size());
  73. }
  74. };
  75. }
  76. typedef std::shared_ptr<hv::HttpResponseWriter> HttpResponseWriterPtr;
  77. #endif // HV_HTTP_RESPONSE_WRITER_H_