1
0

HttpResponseWriter.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 HttpResponseWriter : public SocketChannel {
  7. public:
  8. HttpResponsePtr resp;
  9. enum State {
  10. SEND_BEGIN,
  11. SEND_HEADER,
  12. SEND_BODY,
  13. SEND_END,
  14. } state;
  15. HttpResponseWriter(hio_t* io, const HttpResponsePtr& _resp)
  16. : SocketChannel(io)
  17. , resp(_resp)
  18. , state(SEND_BEGIN)
  19. {}
  20. ~HttpResponseWriter() {}
  21. int Begin() {
  22. state = SEND_BEGIN;
  23. return 0;
  24. }
  25. int WriteStatus(http_status status_codes) {
  26. resp->status_code = status_codes;
  27. return 0;
  28. }
  29. int WriteHeader(const char* key, const char* value) {
  30. resp->headers[key] = value;
  31. return 0;
  32. }
  33. int EndHeaders(const char* key = NULL, const char* value = NULL) {
  34. if (state != SEND_BEGIN) return -1;
  35. if (key && value) {
  36. resp->headers[key] = value;
  37. }
  38. std::string headers = resp->Dump(true, false);
  39. state = SEND_HEADER;
  40. return write(headers);
  41. }
  42. int WriteBody(const char* buf, int len = -1) {
  43. if (len == -1) len = strlen(buf);
  44. if (state == SEND_BEGIN) {
  45. resp->body.append(buf, len);
  46. return len;
  47. } else {
  48. state = SEND_BODY;
  49. return write(buf, len);
  50. }
  51. }
  52. int WriteBody(const std::string& str) {
  53. return WriteBody(str.c_str(), str.size());
  54. }
  55. int End(const char* buf = NULL, int len = -1) {
  56. if (state == SEND_END) return 0;
  57. int ret = 0;
  58. if (buf) {
  59. ret = WriteBody(buf, len);
  60. }
  61. bool is_dump_headers = true;
  62. bool is_dump_body = true;
  63. if (state == SEND_HEADER) {
  64. is_dump_headers = false;
  65. } else if (state == SEND_BODY) {
  66. is_dump_headers = false;
  67. is_dump_body = false;
  68. }
  69. if (is_dump_body) {
  70. std::string msg = resp->Dump(is_dump_headers, is_dump_body);
  71. ret = write(msg);
  72. }
  73. state = SEND_END;
  74. if (!resp->IsKeepAlive()) {
  75. close();
  76. }
  77. return ret;
  78. }
  79. int End(const std::string& str) {
  80. return End(str.c_str(), str.size());
  81. }
  82. };
  83. }
  84. typedef std::shared_ptr<hv::HttpResponseWriter> HttpResponseWriterPtr;
  85. #endif // HV_HTTP_RESPONSE_WRITER_H_