nutt_web/http/response/
mod.rs

1pub mod responder;
2
3use crate::http::response::responder::Responder;
4use crate::http::status::StatusCode;
5use crate::http::{HttpBody, HttpHeader};
6use serde::Serialize;
7use serde_json::json;
8use std::fmt::Display;
9
10pub struct Response {
11    header: HttpHeader,
12    status: StatusCode,
13    body: HttpBody,
14}
15
16impl Display for Response {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        let resp = format!(
19            "HTTP/1.1 {}\r\n{}\r\n{}\r\n\r\n",
20            self.status,
21            self.header,
22            json!(self.body.body)
23        );
24        write!(f, "{}", resp)
25    }
26}
27pub struct ResponseBuilder {
28    status: StatusCode,
29    header: HttpHeader,
30    body: HttpBody,
31}
32
33impl ResponseBuilder {
34    pub fn set_cookie(mut self, key: &str, item: String) -> Self {
35        self.header
36            .headers
37            .insert("Set-Cookie".to_string(), format!("{}={};", key, item));
38        self
39    }
40}
41
42impl ResponseBuilder {
43    pub fn new<T: Serialize + Clone + Send>(status_code: StatusCode, response: T) -> Self {
44        Self {
45            status: status_code,
46            header: HttpHeader::new(response.clone()),
47            body: HttpBody::new(serde_json::to_value(response).unwrap()),
48        }
49    }
50
51    pub fn build(self) -> Response {
52        Response {
53            status: self.status,
54            header: self.header,
55            body: self.body,
56        }
57    }
58}
59
60impl Responder for Response {
61    fn into_response(self) -> Response {
62        self
63    }
64}