~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 (3) hide show
  1. examples/actix.rs +4 -2
  2. examples/basic.rs +1 -1
  3. src/lib.rs +3 -3
examples/actix.rs CHANGED
@@ -4,7 +4,7 @@ extern crate rust_embed;
4
4
  extern crate mime_guess;
5
5
 
6
6
  use actix_web::http::Method;
7
- use actix_web::{server, App, HttpRequest, HttpResponse};
7
+ use actix_web::{server, App, Body, HttpRequest, HttpResponse};
8
8
  use mime_guess::guess_mime_type;
9
9
 
10
10
  #[derive(RustEmbed)]
@@ -13,7 +13,9 @@ struct Asset;
13
13
 
14
14
  fn handle_embedded_file(path: &str) -> HttpResponse {
15
15
  match Asset::get(path) {
16
+ Some(content) => HttpResponse::Ok()
16
- Some(content) => HttpResponse::Ok().content_type(guess_mime_type(path).as_ref()).body(content),
17
+ .content_type(guess_mime_type(path).as_ref())
18
+ .body(Body::from_slice(content.as_ref())),
17
19
  None => HttpResponse::NotFound().body("404 Not Found"),
18
20
  }
19
21
  }
examples/basic.rs CHANGED
@@ -7,5 +7,5 @@ struct Asset;
7
7
 
8
8
  fn main() {
9
9
  let index_html = Asset::get("index.html").unwrap();
10
- println!("{:?}", std::str::from_utf8(&index_html));
10
+ println!("{:?}", std::str::from_utf8(index_html.as_ref()));
11
11
  }
src/lib.rs CHANGED
@@ -15,7 +15,7 @@ use syn::*;
15
15
  fn generate_assets(ident: &syn::Ident, folder_path: String) -> quote::Tokens {
16
16
  quote!{
17
17
  impl #ident {
18
- pub fn get(file_path: &str) -> Option<Vec<u8>> {
18
+ pub fn get(file_path: &str) -> Option<impl AsRef<[u8]>> {
19
19
  use std::fs::File;
20
20
  use std::io::Read;
21
21
  use std::path::Path;
@@ -63,13 +63,13 @@ fn generate_assets(ident: &syn::Ident, folder_path: String) -> quote::Tokens {
63
63
  let key = if std::path::MAIN_SEPARATOR == '\\' { key.replace('\\', "/") } else { key };
64
64
  let canonical_path_str = canonical_path.to_str();
65
65
  let value = quote!{
66
- #key => Some(include_bytes!(#canonical_path_str).to_vec()),
66
+ #key => Some(&include_bytes!(#canonical_path_str)[..]),
67
67
  };
68
68
  values.push(value);
69
69
  }
70
70
  quote!{
71
71
  impl #ident {
72
- pub fn get(file_path: &str) -> Option<Vec<u8>> {
72
+ pub fn get(file_path: &str) -> Option<impl AsRef<[u8]>> {
73
73
  match file_path {
74
74
  #(#values)*
75
75
  _ => None,