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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use std::marker::PhantomData;
use async_trait::async_trait;
use rust_embed::RustEmbed;
use crate::{
http::{header, Method, StatusCode},
Endpoint, Error, Request, Response,
};
pub struct EmbeddedFileEndpoint<E: RustEmbed + Send + Sync> {
_embed: PhantomData<E>,
path: String,
}
impl<E: RustEmbed + Send + Sync> EmbeddedFileEndpoint<E> {
pub fn new(path: &str) -> Self {
EmbeddedFileEndpoint {
_embed: PhantomData,
path: path.to_owned(),
}
}
}
#[async_trait]
impl<E: RustEmbed + Send + Sync> Endpoint for EmbeddedFileEndpoint<E> {
type Output = Response;
async fn call(&self, req: Request) -> Result<Self::Output, Error> {
if req.method() != Method::GET {
return Err(StatusCode::METHOD_NOT_ALLOWED.into());
}
match E::get(&self.path) {
Some(content) => {
let hash = hex::encode(content.metadata.sha256_hash());
if req
.headers()
.get(header::IF_NONE_MATCH)
.map(|etag| etag.to_str().unwrap_or("000000").eq(&hash))
.unwrap_or(false)
{
return Err(StatusCode::NOT_MODIFIED.into());
}
let body: Vec<u8> = content.data.into();
let mime = mime_guess::from_path(&self.path).first_or_octet_stream();
Ok(Response::builder()
.header(header::CONTENT_TYPE, mime.as_ref())
.header(header::ETAG, hash)
.body(body))
}
None => Err(StatusCode::NOT_FOUND.into()),
}
}
}
pub struct EmbeddedFilesEndpoint<E: RustEmbed + Send + Sync> {
_embed: PhantomData<E>,
}
impl<E: RustEmbed + Sync + Send> Default for EmbeddedFilesEndpoint<E> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<E: RustEmbed + Send + Sync> EmbeddedFilesEndpoint<E> {
pub fn new() -> Self {
EmbeddedFilesEndpoint {
_embed: PhantomData,
}
}
}
#[async_trait]
impl<E: RustEmbed + Send + Sync> Endpoint for EmbeddedFilesEndpoint<E> {
type Output = Response;
async fn call(&self, req: Request) -> Result<Self::Output, Error> {
let mut path = req
.uri()
.path()
.trim_start_matches('/')
.trim_end_matches('/')
.to_string();
if path.is_empty() {
path = "index.html".to_string();
}
let path = path.as_ref();
EmbeddedFileEndpoint::<E>::new(path).call(req).await
}
}