~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/actix.rs +32 -7
examples/actix.rs CHANGED
@@ -1,13 +1,38 @@
1
1
  extern crate actix_web;
2
+ #[macro_use]
2
- use actix_web::{server, App, HttpRequest};
3
+ extern crate rust_embed;
3
4
 
5
+ use actix_web::{App, HttpRequest, HttpResponse, server};
6
+ use actix_web::http::Method;
7
+
8
+ #[derive(RustEmbed)]
9
+ #[folder = "examples/public/"]
10
+ struct Asset;
11
+
12
+ fn handle_embedded_file(path: &str) -> HttpResponse {
13
+ match Asset::get(path) {
14
+ Some(content) => HttpResponse::Ok().body(content),
15
+ None => HttpResponse::NotFound().body("404 Not Found"),
16
+ }
17
+ }
18
+
4
- fn index(_req: HttpRequest) -> &'static str {
19
+ fn index(_req: HttpRequest) -> HttpResponse {
20
+ handle_embedded_file("index.html")
21
+ }
22
+
23
+ fn dist(req: HttpRequest) -> HttpResponse {
24
+ let path = &req.path()["/dist/".len()..];
5
- "Hello world!"
25
+ handle_embedded_file(path)
6
26
  }
7
27
 
8
28
  fn main() {
29
+ server::new(|| {
9
- server::new(|| App::new().resource("/", |r| r.f(index)))
30
+ App::new().route("/", Method::GET, index).route(
31
+ "/dist{_:.*}",
32
+ Method::GET,
33
+ dist,
34
+ )
10
- .bind("127.0.0.1:8000")
35
+ }).bind("127.0.0.1:8000")
11
- .unwrap()
36
+ .unwrap()
12
- .run();
37
+ .run();
13
38
  }