Created
January 12, 2022 02:22
-
-
Save jamen/d8f10c4baee91febd2ed4405e75611ad to your computer and use it in GitHub Desktop.
Semi-cursed macro that serves embedded files as warp filters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro_rules! include_file_as_resp { | |
($file:expr) => {{ | |
use headers::HeaderMapExt; | |
let body = include_bytes!($file).as_slice(); | |
let mut resp = warp::reply::Response::new(body.into()); | |
let mime = mime_guess::from_path($file).first_or_octet_stream(); | |
resp.headers_mut().typed_insert(headers::ContentLength(body.len() as u64)); | |
resp.headers_mut().typed_insert(headers::ContentType::from(mime)); | |
resp.headers_mut().typed_insert(headers::AcceptRanges::bytes()); | |
resp | |
}} | |
} | |
macro_rules! include_file_as_filter { | |
($route:literal -> $file:expr) => {{ | |
use warp::Filter; | |
if $route != "" { | |
warp::path($route).and(warp::path::end()).boxed() | |
} else { | |
warp::path::end().boxed() | |
}.map(|| include_file_as_resp!($file)) | |
}} | |
} | |
macro_rules! include_files_as_filter { | |
($fr:literal -> $ff:expr, $($r:literal -> $f:expr),* $(,)?) => {{ | |
use warp::Filter; | |
let routes = include_file_as_filter!($fr -> $ff); | |
$(let routes = routes.or(include_file_as_filter!($r -> $f));)* | |
warp::get().and(routes) | |
}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment