blob: 7a8102578e378c3d6c236a4134292598b441c59b [file] [log] [blame]
[email protected]c700fd152013-07-23 21:29:111// 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
5#include "net/server/http_server_response_info.h"
6
7#include "base/format_macros.h"
8#include "base/strings/stringprintf.h"
9#include "net/http/http_request_headers.h"
10
11namespace net {
12
13HttpServerResponseInfo::HttpServerResponseInfo() : status_code_(HTTP_OK) {}
14
15HttpServerResponseInfo::HttpServerResponseInfo(HttpStatusCode status_code)
16 : status_code_(status_code) {}
17
vmpstracd23b72016-02-26 21:08:5518HttpServerResponseInfo::HttpServerResponseInfo(
19 const HttpServerResponseInfo& other) = default;
20
Chris Watkins7a41d3552017-12-01 02:13:2721HttpServerResponseInfo::~HttpServerResponseInfo() = default;
[email protected]c700fd152013-07-23 21:29:1122
23// static
24HttpServerResponseInfo HttpServerResponseInfo::CreateFor404() {
25 HttpServerResponseInfo response(HTTP_NOT_FOUND);
26 response.SetBody(std::string(), "text/html");
27 return response;
28}
29
30// static
31HttpServerResponseInfo HttpServerResponseInfo::CreateFor500(
32 const std::string& body) {
33 HttpServerResponseInfo response(HTTP_INTERNAL_SERVER_ERROR);
34 response.SetBody(body, "text/html");
35 return response;
36}
37
38void HttpServerResponseInfo::AddHeader(const std::string& name,
39 const std::string& value) {
40 headers_.push_back(std::make_pair(name, value));
41}
42
43void HttpServerResponseInfo::SetBody(const std::string& body,
44 const std::string& content_type) {
45 DCHECK(body_.empty());
46 body_ = body;
byungchul38c3ae72014-08-25 23:27:4647 SetContentHeaders(body.length(), content_type);
48}
49
50void HttpServerResponseInfo::SetContentHeaders(
51 size_t content_length,
52 const std::string& content_type) {
[email protected]c700fd152013-07-23 21:29:1153 AddHeader(HttpRequestHeaders::kContentLength,
byungchul38c3ae72014-08-25 23:27:4654 base::StringPrintf("%" PRIuS, content_length));
[email protected]c700fd152013-07-23 21:29:1155 AddHeader(HttpRequestHeaders::kContentType, content_type);
56}
57
58std::string HttpServerResponseInfo::Serialize() const {
59 std::string response = base::StringPrintf(
60 "HTTP/1.1 %d %s\r\n", status_code_, GetHttpReasonPhrase(status_code_));
61 Headers::const_iterator header;
62 for (header = headers_.begin(); header != headers_.end(); ++header)
63 response += header->first + ":" + header->second + "\r\n";
64
65 return response + "\r\n" + body_;
66}
67
68HttpStatusCode HttpServerResponseInfo::status_code() const {
69 return status_code_;
70}
71
72const std::string& HttpServerResponseInfo::body() const {
73 return body_;
74}
75
76} // namespace net