gato_core/kernel/
response.rs1use std::collections::HashMap;
2use serde_json::Value;
3use crate::kernel::singleton::{new_singleton, Singleton};
4
5pub struct Response {
6 code: i32,
7 headers: HashMap<String, String>,
8 body: String
9}
10
11static mut HTTP_HEADERS : Singleton<HashMap<String, String>> = new_singleton();
12
13impl Response {
14
15 fn clone(&self) -> Self {
16 return Response{
17 code: self.code.clone(), headers: self.headers.clone(), body: self.body.clone()
18 };
19 }
20
21 pub fn add_default_header(name: &str, value: &str) {
22 unsafe {
23 if HTTP_HEADERS.is_none() {
24 HTTP_HEADERS.set_instance(HashMap::new());
25 }
26 let mut headers = HTTP_HEADERS.get_instance().clone();
27 headers.insert(name.to_string(), value.to_string());
28 HTTP_HEADERS.set_instance(headers);
29 }
30 }
31
32 pub fn new() -> Self {
33 let headers = unsafe {
34 if HTTP_HEADERS.is_none() {
35 HashMap::new()
36 } else {
37 HTTP_HEADERS.get_instance().clone()
38 }
39 };
40 return Response{ code: 200, headers, body: String::new() };
41 }
42
43 pub fn json(&mut self, body: Value) -> Self {
44 self.headers.insert("Content-Type".to_owned(), "application/json".to_owned());
45 self.body = body.to_string();
46 return self.clone();
47 }
48
49 pub fn raw(&mut self, body: &str) -> Self {
50 let content_type = "Content-Type".to_owned();
51 if !self.headers.contains_key(&content_type) {
52 self.headers.insert(content_type, "text/html".to_owned());
53 }
54 self.body = body.to_string();
55 return self.clone();
56 }
57
58 pub fn header(&mut self, name: &str, value: &str) -> &mut Self {
59 self.headers.insert(name.to_string(), value.to_string());
60 return self;
61 }
62
63 pub fn status(&mut self, code: i32) -> &mut Self {
64 self.code = code;
65 return self;
66 }
67
68 pub fn get_body(&self) -> String {
69 return self.body.clone();
70 }
71
72 pub fn get_headers(&self) -> HashMap<String, String> {
73 return self.headers.clone();
74 }
75
76 pub fn get_code(&self) -> i32 {
77 return self.code;
78 }
79
80}