use std::io::{self, Write};
use crate::body::Body;
use crate::headers::Headers;
use crate::json::Json;
use crate::status::Status;
#[derive(Debug)]
pub struct Response {
pub status: Status,
pub headers: Headers,
body: Body,
}
impl Response {
pub fn new(status: Status) -> Response {
Response {
status,
headers: Headers::new(),
body: Body::empty(),
}
}
pub fn ok() -> Response {
Response::new(Status::OK)
}
pub fn text<S: Into<String>>(body: S) -> Response {
Response::bytes("text/plain; charset=utf-8", body.into())
}
pub fn html<S: Into<String>>(body: S) -> Response {
Response::bytes("text/html; charset=utf-8", body.into())
}
pub fn json(value: &Json) -> Response {
Response::bytes("application/json", value.to_string())
}
pub fn bytes<B: Into<Body>>(content_type: &str, body: B) -> Response {
let mut res = Response::new(Status::OK);
res.headers.set("Content-Type", content_type);
res.body = body.into();
res
}
pub fn no_content() -> Response {
Response::new(Status::NO_CONTENT)
}
pub fn redirect(location: &str) -> Response {
let mut res = Response::new(Status::FOUND);
res.headers.set("Location", location);
res
}
pub fn not_found() -> Response {
Response::error(Status::NOT_FOUND, "not found")
}
pub fn error(status: Status, message: &str) -> Response {
let value = Json::object(vec![
("error", Json::from(message)),
("status", Json::from(status.code() as i64)),
]);
Response::json(&value).with_status(status)
}
pub fn with_status(mut self, status: Status) -> Response {
self.status = status;
self
}
pub fn header(mut self, name: &str, value: &str) -> Response {
self.headers.set(name, value);
self
}
pub fn with_body<B: Into<Body>>(mut self, body: B) -> Response {
self.body = body.into();
self
}
pub fn body(&self) -> &Body {
&self.body
}
pub fn into_body(self) -> Body {
self.body
}
pub fn write_to<W: Write>(
self,
out: &mut W,
head_only: bool,
keep_alive: bool,
) -> io::Result<()> {
let Response {
status,
headers,
body,
} = self;
let suppress_body = head_only || status.body_forbidden();
let length = body.len();
let keep_alive = keep_alive && length.is_some();
write!(out, "HTTP/1.1 {} {}\r\n", status.code(), status.reason())?;
for (name, value) in headers.iter() {
if name.eq_ignore_ascii_case("Content-Length")
|| name.eq_ignore_ascii_case("Connection")
|| name.eq_ignore_ascii_case("Transfer-Encoding")
{
continue;
}
write!(out, "{name}: {value}\r\n")?;
}
if !status.body_forbidden() {
if let Some(length) = length {
write!(out, "Content-Length: {length}\r\n")?;
}
}
write!(
out,
"Connection: {}\r\n",
if keep_alive { "keep-alive" } else { "close" }
)?;
out.write_all(b"\r\n")?;
if !suppress_body {
body.write_to(out)?;
}
out.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn render(res: Response, head_only: bool, keep_alive: bool) -> String {
let mut buf = Vec::new();
res.write_to(&mut buf, head_only, keep_alive).unwrap();
String::from_utf8(buf).unwrap()
}
fn body_text(res: &Response) -> String {
String::from_utf8(res.body().as_bytes().unwrap().to_vec()).unwrap()
}
#[test]
fn writes_status_line_and_body() {
let out = render(Response::text("hi"), false, true);
assert!(out.starts_with("HTTP/1.1 200 OK\r\n"));
assert!(out.contains("Content-Type: text/plain; charset=utf-8\r\n"));
assert!(out.contains("Content-Length: 2\r\n"));
assert!(out.ends_with("\r\n\r\nhi"));
}
#[test]
fn head_keeps_headers_but_drops_the_body() {
let out = render(Response::text("hello"), true, true);
assert!(out.contains("Content-Length: 5\r\n"));
assert!(out.ends_with("\r\n\r\n"));
assert!(!out.contains("hello"));
}
#[test]
fn no_content_has_neither_body_nor_length() {
let out = render(Response::no_content(), false, true);
assert!(out.starts_with("HTTP/1.1 204 No Content\r\n"));
assert!(!out.contains("Content-Length"));
}
#[test]
fn connection_header_reflects_keep_alive() {
assert!(render(Response::ok(), false, true).contains("Connection: keep-alive\r\n"));
assert!(render(Response::ok(), false, false).contains("Connection: close\r\n"));
}
#[test]
fn handler_cannot_override_framing_headers() {
let res = Response::text("abc")
.header("Content-Length", "999")
.header("Connection", "keep-alive")
.header("Transfer-Encoding", "chunked");
let out = render(res, false, false);
assert!(out.contains("Content-Length: 3\r\n"));
assert!(!out.contains("999"));
assert!(!out.contains("Transfer-Encoding"));
assert!(out.contains("Connection: close\r\n"));
}
#[test]
fn error_bodies_are_valid_json_even_with_quotes() {
let res = Response::error(Status::BAD_REQUEST, "he said \"no\"\n");
let parsed = Json::parse(&body_text(&res)).unwrap();
assert_eq!(parsed.get("status").and_then(Json::as_i64), Some(400));
assert_eq!(
parsed.get("error").and_then(Json::as_str),
Some("he said \"no\"\n")
);
}
#[test]
fn json_response_sets_the_content_type() {
let res = Response::json(&Json::object(vec![("a", Json::from(1i64))]));
assert_eq!(res.headers.get("Content-Type"), Some("application/json"));
assert_eq!(body_text(&res), r#"{"a":1}"#);
}
#[test]
fn the_body_is_reached_through_the_accessor() {
let res = Response::ok().with_body("replaced");
assert_eq!(res.body().len(), Some(8));
assert_eq!(body_text(&res), "replaced");
assert_eq!(res.into_body().into_bytes().unwrap(), b"replaced");
}
#[test]
fn debug_does_not_print_the_body() {
let text = format!("{:?}", Response::text("hunter2"));
assert!(text.contains("Body(7 bytes)"), "got {text}");
assert!(!text.contains("hunter2"), "got {text}");
}
}