~repos /rust-embed

#rust#proc-macro#http

git clone https://pyrossh.dev/repos/rust-embed.git
Discussions: https://groups.google.com/g/rust-embed-devs

rust macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.


Files changed (1) hide show
  1. examples/axum.rs +18 -12
examples/axum.rs CHANGED
@@ -11,42 +11,47 @@ use std::net::SocketAddr;
11
11
 
12
12
  #[tokio::main]
13
13
  async fn main() {
14
- // build our application with a route
14
+ // Define our app routes, including a fallback option for anything not matched.
15
15
  let app = Router::new()
16
- .route("/hello", get(helloworld))
17
- // handle static files with rust_embed
18
16
  .route("/", get(index_handler))
19
17
  .route("/index.html", get(index_handler))
20
- .route("/dist/", static_handler.into_service())
18
+ .route("/dist/*file", static_handler.into_service())
21
- .fallback(static_handler.into_service());
19
+ .fallback(get(not_found));
22
20
 
23
- // run it
21
+ // Start listening on the given address.
24
22
  let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
25
23
  println!("listening on {}", addr);
26
24
  axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
27
25
  }
28
26
 
29
- async fn helloworld() -> Html<&'static str> {
30
- Html("<h1>Hello, World!</h1>")
31
- }
32
-
33
- // serve index.html from examples/public/index.html
27
+ // We use static route matchers ("/" and "/index.html") to serve our home
28
+ // page.
34
29
  async fn index_handler() -> impl IntoResponse {
35
30
  static_handler("/index.html".parse::<Uri>().unwrap()).await
36
31
  }
37
32
 
33
+ // We use a wildcard matcher ("/dist/*file") to match against everything
38
- // static_handler is a handler that serves static files from the
34
+ // within our defined assets directory. This is the directory on our Asset
35
+ // struct below, where folder = "examples/public/".
39
36
  async fn static_handler(uri: Uri) -> impl IntoResponse {
40
37
  let mut path = uri.path().trim_start_matches('/').to_string();
38
+
41
39
  if path.starts_with("dist/") {
42
40
  path = path.replace("dist/", "");
43
41
  }
42
+
44
43
  StaticFile(path)
45
44
  }
46
45
 
46
+ // Finally, we use a fallback route for anything that didn't match.
47
+ async fn not_found() -> Html<&'static str> {
48
+ Html("<h1>404</h1><p>Not Found</p>")
49
+ }
50
+
47
51
  #[derive(RustEmbed)]
48
52
  #[folder = "examples/public/"]
49
53
  struct Asset;
54
+
50
55
  pub struct StaticFile<T>(pub T);
51
56
 
52
57
  impl<T> IntoResponse for StaticFile<T>
@@ -55,6 +60,7 @@ where
55
60
  {
56
61
  fn into_response(self) -> Response {
57
62
  let path = self.0.into();
63
+
58
64
  match Asset::get(path.as_str()) {
59
65
  Some(content) => {
60
66
  let body = boxed(Full::from(content.data));