Skip to main content

http/response/
builder.rs

1use std::{collections::HashMap, io::BufReader};
2
3use crate::{HttpResponse, stream};
4
5pub struct HttpResponseBuilder {
6    headers: HashMap<Box<str>, Box<str>>,
7    status: u16,
8    body: Option<Box<[u8]>>,
9    version: f32,
10}
11
12impl HttpResponseBuilder {
13    pub fn new() -> Self {
14        Self {
15            headers: HashMap::new(),
16            status: 200,
17            body: None,
18            version: 1.0,
19        }
20    }
21
22    pub fn header(mut self, k: impl Into<Box<str>>, v: impl Into<Box<str>>) -> Self {
23        self.headers.insert(k.into(), v.into());
24        self
25    }
26
27    pub fn version(mut self, v: f32) -> Self {
28        self.version = v;
29        self
30    }
31
32    pub fn status(mut self, code: u16) -> Self {
33        self.status = code;
34        self
35    }
36
37    pub fn body(mut self, body: impl Into<Box<[u8]>>) -> Self {
38        self.body = Some(body.into());
39        self
40    }
41
42    pub fn build(self) -> HttpResponse {
43        HttpResponse {
44            body: self.body,
45            status: self.status,
46            headers: self.headers,
47            stream: BufReader::new(stream::dummy()),
48            version: self.version,
49        }
50    }
51}
52
53impl Default for HttpResponseBuilder {
54    fn default() -> Self {
55        Self::new()
56    }
57}