server_lib/server/
response_builder.rs

1pub struct ResponseBuilder {
2    response_code: String,
3    cors_policy: String,
4    content_type: String,
5    content: String,
6
7    other_headers: Vec<(String, String)>,
8}
9
10impl ResponseBuilder {
11    pub fn new() -> Self {
12        ResponseBuilder {
13            response_code: "".to_string(),
14            cors_policy: "".to_string(),
15            content_type: "".to_string(),
16            content: "".to_string(),
17            other_headers: vec![],
18        }
19    }
20
21    pub fn set_response_code<S>(&mut self, code: S) -> &mut Self
22    where
23        S: Into<String>,
24    {
25        self.response_code = format!("HTTP/1.1 {}\r\n", code.into());
26        self
27    }
28
29    pub fn set_content<S>(&mut self, content: S) -> &mut Self
30    where
31        S: Into<String>,
32    {
33        let content = content.into();
34        if content.len() == 0 {
35            return self;
36        }
37
38        self.content = format!("Content-Length: {}\r\n\r\n{}", content.len(), content);
39        self
40    }
41
42    pub fn set_cors_polisy<S>(&mut self, policy: S) -> &mut Self
43    where
44        S: Into<String>,
45    {
46        self.cors_policy = format!("Access-Control-Allow-Origin: {}\r\n", policy.into());
47        self
48    }
49
50    pub fn set_content_type<S>(&mut self, content_type: S) -> &mut Self
51    where
52        S: Into<String>,
53    {
54        self.content_type = format!("Content-Type: {}; charset=UTF-8\r\n", content_type.into());
55        self
56    }
57
58    pub fn add_other_header<S>(&mut self, key_value: (S, S)) -> &mut Self
59    where
60        S: Into<String>,
61    {
62        self.other_headers
63            .push((key_value.0.into(), key_value.1.into()));
64        self
65    }
66
67    pub fn build(&self) -> String {
68        let mut other_headers = Vec::new();
69
70        for (key, value) in &self.other_headers {
71            other_headers.push(format!("{}:{}\r\n", key, value));
72        }
73
74        let other_headers = other_headers.concat();
75
76        let response = format!(
77            "{}{}{}{}{}",
78            self.response_code, self.cors_policy, other_headers, self.content_type, self.content,
79        );
80
81        response
82    }
83}
84
85// our response
86// HTTP/1.1 200 OK
87// Date: Mon, 01 Dec 2008 00:23:53 GMT
88// Server: Apache/2
89// Access-Control-Allow-Origin: *
90// Keep-Alive: timeout=2, max=100
91// Connection: Keep-Alive
92// Transfer-Encoding: chunked
93// Content-Type: application/json
94
95// request from browser
96// GET /resources/public-data/ HTTP/1.1
97// Host: bar.other
98// User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
99// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
100// Accept-Language: en-us,en;q=0.5
101// Accept-Encoding: gzip,deflate
102// Connection: keep-alive
103// Origin: https://foo.example