~repos /rust-embed
git clone https://pyrossh.dev/repos/rust-embed.git
rust macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.
b5e57f1e
—
frederikhors 3 years ago
use Response everywhere
- examples/axum-spa/main.rs +33 -42
examples/axum-spa/main.rs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
use axum::{
|
|
2
|
-
|
|
2
|
+
body::{boxed, Full},
|
|
3
|
-
|
|
3
|
+
handler::Handler,
|
|
4
|
-
|
|
4
|
+
http::{header, StatusCode, Uri},
|
|
5
|
-
|
|
5
|
+
response::Response,
|
|
6
|
-
|
|
6
|
+
routing::Router,
|
|
7
7
|
};
|
|
8
8
|
use rust_embed::RustEmbed;
|
|
9
9
|
use std::net::SocketAddr;
|
|
@@ -16,57 +16,48 @@ struct Assets;
|
|
|
16
16
|
|
|
17
17
|
#[tokio::main]
|
|
18
18
|
async fn main() {
|
|
19
|
-
|
|
19
|
+
let app = Router::new().fallback(static_handler.into_service());
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
22
|
-
|
|
22
|
+
println!("listening on {}", addr);
|
|
23
|
-
axum::Server::bind(&addr)
|
|
24
|
-
|
|
23
|
+
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
|
|
25
|
-
.await
|
|
26
|
-
.unwrap();
|
|
27
24
|
}
|
|
28
25
|
|
|
29
26
|
async fn static_handler(uri: Uri) -> Response {
|
|
30
|
-
|
|
27
|
+
let path = uri.path().trim_start_matches('/');
|
|
31
28
|
|
|
32
|
-
|
|
29
|
+
if path.is_empty() || path == INDEX_HTML {
|
|
33
|
-
|
|
30
|
+
return index_html().await;
|
|
34
|
-
|
|
31
|
+
}
|
|
35
32
|
|
|
36
|
-
|
|
33
|
+
match Assets::get(path) {
|
|
37
|
-
|
|
34
|
+
Some(content) => {
|
|
38
|
-
|
|
35
|
+
let body = boxed(Full::from(content.data));
|
|
39
|
-
|
|
36
|
+
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
|
40
37
|
|
|
41
|
-
Response::builder()
|
|
42
|
-
|
|
38
|
+
Response::builder().header(header::CONTENT_TYPE, mime.as_ref()).body(body).unwrap()
|
|
43
|
-
.body(body)
|
|
44
|
-
.unwrap()
|
|
45
|
-
|
|
39
|
+
}
|
|
46
|
-
|
|
40
|
+
None => {
|
|
47
|
-
|
|
41
|
+
if path.contains('.') {
|
|
48
|
-
|
|
42
|
+
return not_found().await;
|
|
49
|
-
|
|
43
|
+
}
|
|
50
44
|
|
|
51
|
-
|
|
45
|
+
index_html().await
|
|
52
|
-
}
|
|
53
46
|
}
|
|
47
|
+
}
|
|
54
48
|
}
|
|
55
49
|
|
|
56
50
|
async fn index_html() -> Response {
|
|
57
|
-
|
|
51
|
+
match Assets::get(INDEX_HTML) {
|
|
58
|
-
|
|
52
|
+
Some(content) => {
|
|
59
|
-
|
|
53
|
+
let body = boxed(Full::from(content.data));
|
|
60
54
|
|
|
61
|
-
Response::builder()
|
|
62
|
-
|
|
55
|
+
Response::builder().header(header::CONTENT_TYPE, "text/html").body(body).unwrap()
|
|
63
|
-
.body(body)
|
|
64
|
-
.unwrap()
|
|
65
|
-
}
|
|
66
|
-
None => not_found().await.into_response(),
|
|
67
56
|
}
|
|
57
|
+
None => not_found().await,
|
|
58
|
+
}
|
|
68
59
|
}
|
|
69
60
|
|
|
70
|
-
async fn not_found() ->
|
|
61
|
+
async fn not_found() -> Response {
|
|
71
|
-
|
|
62
|
+
Response::builder().status(StatusCode::NOT_FOUND).body(boxed(Full::from("404"))).unwrap()
|
|
72
63
|
}
|