Created
December 2, 2019 14:08
-
-
Save felipesere/1c9c9b8e80245724827289ca42bc1520 to your computer and use it in GitHub Desktop.
Trying to server static files from a subfolder that is given as part of a struct that implements `Endpoint`
This file contains hidden or 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
pub struct StaticFilesV2 { | |
pub root: String, | |
} | |
pub(crate) type BoxFuture<'a, T> = std::pin::Pin<Box<dyn Future<Output = T> + Send + 'a>>; | |
impl <STATE: Send + Sync + 'static> Endpoint<STATE> for StaticFilesV2 { | |
type Fut = BoxFuture<'static, Response>; | |
fn call(&self, req: Request<STATE>) -> Self::Fut { | |
let protected_request = Arc::new(Mutex::new( (req, self.root.clone()) )); | |
Box::pin(async { | |
let (request, root) = &*protected_request.lock().await; | |
let filename: String = request.param("filename").unwrap(); | |
log::warn!("The filename was: {}", filename); | |
let real_filename = &format!("{}/{}",root , filename); | |
match async_std::fs::read_to_string(&real_filename).await { | |
Ok(content) => { | |
let path = std::path::Path::new(&real_filename); | |
match path.extension() { | |
Some(extension) => { | |
let content_type = format!("text/{}", (*extension).to_str().unwrap()); | |
Response::new(200).body_string(content).set_header("Content-Type", content_type) | |
}, | |
None => Response::new(200).body_string(content), | |
} | |
}, | |
Err(_) => Response::new(404), | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Current compile error: