1use std::fmt::Display;
2use std::io;
3use std::io::BufWriter;
4use std::net::TcpStream;
5
6use crate::header::Header;
7use crate::status_code::StatusCode;
8
9#[derive(Debug)]
10pub struct Response {
11 writer: BufWriter<TcpStream>,
12 content: String
13}
14
15impl Response {
16 pub fn new(stream: TcpStream) -> Response {
17 Response {
18 writer: BufWriter::new(stream),
19 content: String::new()
20 }
21 }
22
23 pub fn status_code(mut self, status_code: StatusCode) -> Header {
24 let content = match status_code {
25 StatusCode::Ok => "HTTP/1.1 200 Ok\r\n",
26 StatusCode::BadRequest => "HTTP/1.1 400 Bad Request\r\n",
27 StatusCode::NotFound => "HTTP/1.1 404 Not Found\r\n",
28 };
29
30 self.content += &content;
31
32 Header::new(self.writer, self.content)
33 }
34
35 pub fn text<T: Display>(self, text: T) -> io::Result<()> {
36 self.status_code(StatusCode::Ok)
37 .set_header("Content-Type", "text/plain").flush()?
38 .add_to_body(text).flush()?;
39
40 Ok(())
41 }
42
43 pub fn html<H: Display>(self, html: H) -> io::Result<()> {
44 self.status_code(StatusCode::Ok)
45 .set_header("Content-Type", "text/html").flush()?
46 .add_to_body(html).flush()?;
47
48 Ok(())
49 }
50
51 pub fn json<J: Display>(self, json: J) -> io::Result<()> {
52 self.status_code(StatusCode::Ok)
53 .set_header("Content-Type", "application/json").flush()?
54 .add_to_body(json).flush()?;
55
56 Ok(())
57 }
58}
59
60unsafe impl Send for Response { }
61unsafe impl Sync for Response { }