thruster_core/
response.rs

1use std::fmt::{self, Write};
2
3use bytes::BytesMut;
4
5pub struct Response {
6    pub response: Vec<u8>,
7    pub status_message: StatusMessage,
8    pub header_raw: BytesMut
9}
10
11pub enum StatusMessage {
12    Ok,
13    Custom(u32, String)
14}
15
16impl Response {
17    pub fn new() -> Response {
18        Response {
19            response: Vec::new(),
20            status_message: StatusMessage::Ok,
21            header_raw: BytesMut::new()
22        }
23    }
24
25    pub fn status_code(&mut self, code: u32, message: &str) -> &mut Response {
26        self.status_message = StatusMessage::Custom(code, message.to_string());
27        self
28    }
29
30    pub fn header(&mut self, name: &str, val: &str) -> &mut Response {
31        let header_string = templatify! { "" ; name ; ": " ; val ; "\r\n" };
32        self.header_raw.extend_from_slice(header_string.as_bytes());
33
34        self
35    }
36
37    pub fn body(&mut self, s: &str) -> &mut Response {
38        self.response = s.as_bytes().to_vec();
39        self
40    }
41
42    pub fn body_bytes(&mut self, b: &[u8]) -> &mut Response {
43        self.response = b.to_vec();
44        self
45    }
46
47    pub fn body_bytes_from_vec(&mut self, b: Vec<u8>) -> &mut Response {
48        self.response = b;
49        self
50    }
51}
52
53pub fn encode(msg: &Response, buf: &mut BytesMut) {
54    let length = msg.response.len();
55    let now = crate::date::now();
56
57    write!(FastWrite(buf), "\
58        HTTP/1.1 {}\r\n\
59        Content-Length: {}\r\n\
60        Date: {}\r\n\
61    ", msg.status_message, length, now).unwrap();
62
63    buf.extend_from_slice(&msg.header_raw);
64    buf.extend_from_slice(b"\r\n");
65    buf.extend_from_slice(msg.response.as_slice());
66}
67
68impl Default for Response {
69    fn default() -> Response {
70        Response::new()
71    }
72}
73
74// TODO: impl fmt::Write for Vec<u8>
75//
76// Right now `write!` on `Vec<u8>` goes through io::Write and is not super
77// speedy, so inline a less-crufty implementation here which doesn't go through
78// io::Error.
79struct FastWrite<'a>(&'a mut BytesMut);
80
81impl<'a> fmt::Write for FastWrite<'a> {
82    fn write_str(&mut self, s: &str) -> fmt::Result {
83        (*self.0).extend_from_slice(s.as_bytes());
84        Ok(())
85    }
86
87    fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result {
88        fmt::write(self, args)
89    }
90}
91
92impl fmt::Display for StatusMessage {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        match *self {
95            StatusMessage::Ok => f.pad("200 OK"),
96            StatusMessage::Custom(c, ref s) => write!(f, "{} {}", c, s),
97        }
98    }
99}