summaryrefslogtreecommitdiff
path: root/src/handler/staticfile.rs
blob: f208528a8505bf6a82c06002a3f19a9455250410 (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
use crate::{
    handler::{self, Handle},
    request::{Method, Request},
    response::{Body, Response, Status},
};

use std::{ffi::OsString, os::unix::ffi::OsStringExt, path::PathBuf};

use mlua::{FromLua, Value};

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

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("io error: {0}")]
    Io(#[from] io::Error),
}

#[derive(Debug, Clone)]
pub struct StaticFile {
    path: PathBuf,
    mime: String,
}

impl Handle for StaticFile {
    async fn handle(self, request: Request) -> Result<Response, handler::Error> {
        match request.method() {
            Method::Get | Method::Head => match File::open(&self.path).await {
                Ok(file) => {
                    let metadata = file.metadata().await.map_err(Error::Io)?;

                    if metadata.is_file() {
                        Ok(Response::builder()
                            .status(Status::Ok)
                            .headers([
                                ("content-length", format!("{}", metadata.len())),
                                ("content-type", self.mime),
                            ])
                            .body(match request.method() {
                                Method::Get => Body::File(file),
                                Method::Head => Body::Empty,
                            }))
                    } else {
                        Ok(Response::builder()
                            .status(Status::NotFound)
                            .headers([("content-length", "0")])
                            .body(Body::Empty))
                    }
                }
                Err(e) if matches!(e.kind(), io::ErrorKind::NotFound) => Ok(Response::builder()
                    .status(Status::NotFound)
                    .headers([("content-length", "0")])
                    .body(Body::Empty)),
                Err(e) => Err(Error::Io(e))?,
            },
        }
    }
}

impl FromLua for StaticFile {
    fn from_lua(value: mlua::Value, _: &mlua::Lua) -> mlua::Result<Self> {
        match value {
            Value::Table(table) => Ok(Self {
                path: PathBuf::from(OsString::from_vec(
                    table.get::<mlua::String>("path")?.as_bytes().to_vec(),
                )),
                mime: table.get::<String>("mime")?,
            }),
            _ => Err(mlua::Error::runtime("expected table")),
        }
    }
}