server_lib/server/
response_builder.rs1pub 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