flashapi/server/
response.rs

1use crate::server::http::HttpStatus;
2use serde::Serialize;
3use tokio::io::AsyncWriteExt;
4use tokio::net::TcpStream;
5
6pub struct Response {
7    stream: TcpStream,
8}
9
10impl Response {
11    pub fn new(stream: TcpStream) -> Self {
12        Self { stream }
13    }
14
15    pub async fn send(&mut self, status: HttpStatus, body: &str, content_type: &str) {
16        let length = body.len();
17        let status_code = status.code();
18        let response = format!(
19            "HTTP/1.1 {status_code}\r\nContent-Length: {length}\r\nContent-Type: {content_type}\r\nConnection: close\r\n\r\n{body}"
20        );
21
22        let res = self.stream.write_all(response.as_bytes()).await;
23
24        match res {
25            Ok(_) => (),
26            Err(e) => {
27                println!("Error: {e}");
28
29                self.stream.write_all(response.as_bytes()).await.unwrap();
30                return ();
31            }
32        }
33    }
34
35    pub async fn send_json<T: Serialize>(&mut self, status: HttpStatus, data: &T) {
36        if let Ok(body) = serde_json::to_string(data) {
37            self.send(status, &body, "application/json").await;
38        } else {
39            self.send(
40                HttpStatus::InternalServerError,
41                "Internal server error",
42                "text/plain",
43            )
44            .await;
45        }
46    }
47}