http_server_response_info.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/server/http_server_response_info.h"
  5. #include "base/check.h"
  6. #include "base/format_macros.h"
  7. #include "base/strings/stringprintf.h"
  8. #include "net/http/http_request_headers.h"
  9. namespace net {
  10. HttpServerResponseInfo::HttpServerResponseInfo() : status_code_(HTTP_OK) {}
  11. HttpServerResponseInfo::HttpServerResponseInfo(HttpStatusCode status_code)
  12. : status_code_(status_code) {}
  13. HttpServerResponseInfo::HttpServerResponseInfo(
  14. const HttpServerResponseInfo& other) = default;
  15. HttpServerResponseInfo::~HttpServerResponseInfo() = default;
  16. // static
  17. HttpServerResponseInfo HttpServerResponseInfo::CreateFor404() {
  18. HttpServerResponseInfo response(HTTP_NOT_FOUND);
  19. response.SetBody(std::string(), "text/html");
  20. return response;
  21. }
  22. // static
  23. HttpServerResponseInfo HttpServerResponseInfo::CreateFor500(
  24. const std::string& body) {
  25. HttpServerResponseInfo response(HTTP_INTERNAL_SERVER_ERROR);
  26. response.SetBody(body, "text/html");
  27. return response;
  28. }
  29. void HttpServerResponseInfo::AddHeader(const std::string& name,
  30. const std::string& value) {
  31. headers_.push_back(std::make_pair(name, value));
  32. }
  33. void HttpServerResponseInfo::SetBody(const std::string& body,
  34. const std::string& content_type) {
  35. DCHECK(body_.empty());
  36. body_ = body;
  37. SetContentHeaders(body.length(), content_type);
  38. }
  39. void HttpServerResponseInfo::SetContentHeaders(
  40. size_t content_length,
  41. const std::string& content_type) {
  42. AddHeader(HttpRequestHeaders::kContentLength,
  43. base::StringPrintf("%" PRIuS, content_length));
  44. AddHeader(HttpRequestHeaders::kContentType, content_type);
  45. }
  46. std::string HttpServerResponseInfo::Serialize() const {
  47. std::string response = base::StringPrintf(
  48. "HTTP/1.1 %d %s\r\n", status_code_, GetHttpReasonPhrase(status_code_));
  49. Headers::const_iterator header;
  50. for (header = headers_.begin(); header != headers_.end(); ++header)
  51. response += header->first + ":" + header->second + "\r\n";
  52. return response + "\r\n" + body_;
  53. }
  54. HttpStatusCode HttpServerResponseInfo::status_code() const {
  55. return status_code_;
  56. }
  57. const std::string& HttpServerResponseInfo::body() const {
  58. return body_;
  59. }
  60. } // namespace net