summaryrefslogtreecommitdiff
path: root/src/response.rs
blob: 68189fbbdb1af913e4581001a653d8871a9d7da2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
mod builder;

use get::Get;

use std::collections::HashMap;

use tokio::{
    fs::File,
    io::{self, AsyncWrite, AsyncWriteExt},
};

use strum::{Display, EnumString, FromRepr};

use builder::Builder;

#[allow(unreachable_patterns)]
#[derive(Debug, Clone, Copy, Display, EnumString, FromRepr)]
pub enum Status {
    #[strum(to_string = "200 OK", serialize = "OK")]
    Ok = 200,

    #[strum(to_string = "404 Not Found", serialize = "Not Found")]
    NotFound = 404,

    #[strum(
        to_string = "500 Internal Server Error",
        serialize = "Internal ServerError"
    )]
    InternalServerError = 500,
}

#[derive(Debug)]
pub enum Body {
    File(File),
    Buffer(Vec<u8>),
    Empty,
}

#[derive(Debug, Get)]
pub struct Response {
    status: Status,
    headers: HashMap<String, Vec<u8>>,
    body: Body,
}

impl Response {
    pub fn builder() -> Builder {
        Builder::new()
    }
}

impl Response {
    pub async fn serialize<W: AsyncWrite + Unpin>(
        mut self,
        mut writer: W,
    ) -> Result<(), io::Error> {
        writer.write_all(b"HTTP/1.1 ").await?;
        writer.write_all(self.status.to_string().as_bytes()).await?;
        writer.write_all(b"\r\n").await?;

        for (key, value) in &self.headers {
            writer.write_all(key.as_bytes()).await?;
            writer.write_all(b": ").await?;
            writer.write_all(value).await?;
            writer.write_all(b"\r\n").await?;
        }

        writer.write_all(b"\r\n").await?;

        match &mut self.body {
            Body::File(file) => {
                io::copy(file, &mut writer).await?;
            }
            Body::Buffer(buf) => {
                writer.write_all(buf).await?;
            }
            Body::Empty => (),
        }

        Ok(())
    }
}