response.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "response.h"
  2. #include <util/stream/output.h>
  3. #include <util/stream/mem.h>
  4. #include <util/string/cast.h>
  5. THttpResponse& THttpResponse::AddMultipleHeaders(const THttpHeaders& headers) {
  6. for (THttpHeaders::TConstIterator i = headers.Begin(); i != headers.End(); ++i) {
  7. this->Headers.AddHeader(*i);
  8. }
  9. return *this;
  10. }
  11. THttpResponse& THttpResponse::SetContentType(const TStringBuf& contentType) {
  12. Headers.AddOrReplaceHeader(THttpInputHeader("Content-Type", ToString(contentType)));
  13. return *this;
  14. }
  15. void THttpResponse::OutTo(IOutputStream& os) const {
  16. TVector<IOutputStream::TPart> parts;
  17. const size_t FIRST_LINE_PARTS = 3;
  18. const size_t HEADERS_PARTS = Headers.Count() * 4;
  19. const size_t CONTENT_PARTS = 5;
  20. parts.reserve(FIRST_LINE_PARTS + HEADERS_PARTS + CONTENT_PARTS);
  21. // first line
  22. parts.push_back(IOutputStream::TPart(TStringBuf("HTTP/1.1 ")));
  23. parts.push_back(IOutputStream::TPart(HttpCodeStrEx(Code)));
  24. parts.push_back(IOutputStream::TPart::CrLf());
  25. // headers
  26. for (THttpHeaders::TConstIterator i = Headers.Begin(); i != Headers.End(); ++i) {
  27. parts.push_back(IOutputStream::TPart(i->Name()));
  28. parts.push_back(IOutputStream::TPart(TStringBuf(": ")));
  29. parts.push_back(IOutputStream::TPart(i->Value()));
  30. parts.push_back(IOutputStream::TPart::CrLf());
  31. }
  32. char buf[50];
  33. if (!Content.empty()) {
  34. TMemoryOutput mo(buf, sizeof(buf));
  35. mo << Content.size();
  36. parts.push_back(IOutputStream::TPart(TStringBuf("Content-Length: ")));
  37. parts.push_back(IOutputStream::TPart(buf, mo.Buf() - buf));
  38. parts.push_back(IOutputStream::TPart::CrLf());
  39. }
  40. // content
  41. parts.push_back(IOutputStream::TPart::CrLf());
  42. if (!Content.empty()) {
  43. parts.push_back(IOutputStream::TPart(Content));
  44. }
  45. os.Write(parts.data(), parts.size());
  46. }
  47. template <>
  48. void Out<THttpResponse>(IOutputStream& os, const THttpResponse& resp) {
  49. resp.OutTo(os);
  50. }