Need help implementing my custom error handler #2792
-
I need to transform some would-be Why? Because of this:
I looked at both the Can anyone please guide me? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Ok, the farthest I've made is this, but now I find myself fighting the borrow checker: use std::collections::HashMap;
use actix_web::dev::{Service, ServiceResponse};
use actix_web::http::{Method, StatusCode};
use actix_web::{App, HttpResponse, HttpServer};
use actix_web_static_files::ResourceFiles;
use futures_util::FutureExt;
use static_files::Resource;
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let static_files: HashMap<&'static str, Resource> = generate();
let index_html: &[u8] = static_files.get("index.html").unwrap().data;
App::new()
.wrap_fn(move |req, srv| {
srv.call(req).map(|res| {
if let Ok(response) = &res {
let request = response.request();
if response.status() == StatusCode::NOT_FOUND
&& request.method() == Method::GET
&& !(request.path().starts_with("/api/"))
{
return Ok(ServiceResponse::new(
request.clone(),
HttpResponse::Ok().body(index_html),
));
}
}
res
})
})
.service(ResourceFiles::new("/", static_files))
})
.bind("0.0.0.0:8080")?
.run()
.await
} error: lifetime may not live long enough
--> src/main.rs:21:17
|
20 | .wrap_fn(move |req, srv| {
| ---------------
| | |
| | return type of closure `futures_util::future::Map<Pin<Box<dyn futures_util::Future<Output = Result<ServiceResponse, actix_web::Error>>>>, [closure@src/main.rs:21:35: 36:18]>` contains a lifetime `'2`
| lifetime `'1` represents this closure's body
21 | / srv.call(req).map(|res| {
22 | | if let Ok(response) = &res {
23 | | let request = response.request();
24 | |
... |
35 | | res
36 | | })
| |__________________^ returning this value requires that `'1` must outlive `'2`
|
= note: closure implements `Fn`, so references to captured variables can't escape the closure |
Beta Was this translation helpful? Give feedback.
-
Give this a go, it removes a lot of the lifetime problems and is conceptually simpler. |
Beta Was this translation helpful? Give feedback.
Give this a go, it removes a lot of the lifetime problems and is conceptually simpler.
https://docs.rs/actix-web-lab/0.16.1/actix_web_lab/middleware/fn.from_fn.html