response.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #pragma once
  2. #include <library/cpp/http/misc/httpcodes.h>
  3. #include <library/cpp/http/io/stream.h>
  4. #include <util/generic/strbuf.h>
  5. #include <util/string/cast.h>
  6. class THttpHeaders;
  7. class IOutputStream;
  8. class THttpResponse {
  9. public:
  10. THttpResponse() noexcept
  11. : Code(HTTP_OK)
  12. {
  13. }
  14. explicit THttpResponse(HttpCodes code) noexcept
  15. : Code(code)
  16. {
  17. }
  18. template <typename ValueType>
  19. THttpResponse& AddHeader(const TString& name, const ValueType& value) {
  20. return AddHeader(THttpInputHeader(name, ToString(value)));
  21. }
  22. THttpResponse& AddHeader(const THttpInputHeader& header) {
  23. Headers.AddHeader(header);
  24. return *this;
  25. }
  26. template <typename ValueType>
  27. THttpResponse& AddOrReplaceHeader(const TString& name, const ValueType& value) {
  28. return AddOrReplaceHeader(THttpInputHeader(name, ToString(value)));
  29. }
  30. THttpResponse& AddOrReplaceHeader(const THttpInputHeader& header) {
  31. Headers.AddOrReplaceHeader(header);
  32. return *this;
  33. }
  34. THttpResponse& AddMultipleHeaders(const THttpHeaders& headers);
  35. const THttpHeaders& GetHeaders() const {
  36. return Headers;
  37. }
  38. THttpResponse& SetContentType(const TStringBuf& contentType);
  39. /**
  40. * @note If @arg content isn't empty its size is automatically added as a
  41. * "Content-Length" header during output to IOutputStream.
  42. * @see IOutputStream& operator << (IOutputStream&, const THttpResponse&)
  43. */
  44. THttpResponse& SetContent(const TString& content) {
  45. Content = content;
  46. return *this;
  47. }
  48. THttpResponse& SetContent(TString&& content) {
  49. Content = std::move(content);
  50. return *this;
  51. }
  52. TString GetContent() const {
  53. return Content;
  54. }
  55. /**
  56. * @note If @arg content isn't empty its size is automatically added as a
  57. * "Content-Length" header during output to IOutputStream.
  58. * @see IOutputStream& operator << (IOutputStream&, const THttpResponse&)
  59. */
  60. THttpResponse& SetContent(const TString& content, const TStringBuf& contentType) {
  61. return SetContent(content).SetContentType(contentType);
  62. }
  63. HttpCodes HttpCode() const {
  64. return Code;
  65. }
  66. THttpResponse& SetHttpCode(HttpCodes code) {
  67. Code = code;
  68. return *this;
  69. }
  70. void OutTo(IOutputStream& out) const;
  71. private:
  72. HttpCodes Code;
  73. THttpHeaders Headers;
  74. TString Content;
  75. };