response.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. TString GetContent() const {
  49. return Content;
  50. }
  51. /**
  52. * @note If @arg content isn't empty its size is automatically added as a
  53. * "Content-Length" header during output to IOutputStream.
  54. * @see IOutputStream& operator << (IOutputStream&, const THttpResponse&)
  55. */
  56. THttpResponse& SetContent(const TString& content, const TStringBuf& contentType) {
  57. return SetContent(content).SetContentType(contentType);
  58. }
  59. HttpCodes HttpCode() const {
  60. return Code;
  61. }
  62. THttpResponse& SetHttpCode(HttpCodes code) {
  63. Code = code;
  64. return *this;
  65. }
  66. void OutTo(IOutputStream& out) const;
  67. private:
  68. HttpCodes Code;
  69. THttpHeaders Headers;
  70. TString Content;
  71. };