Update 'fairings' example for async.

This commit is contained in:
Jeb Rosen 2019-08-04 15:36:55 -07:00 committed by Sergio Benitez
parent bc404f1f6d
commit 094146b929
1 changed files with 22 additions and 16 deletions

View File

@ -35,7 +35,10 @@ impl Fairing for Counter {
} }
} }
fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) { fn on_response<'a, 'r>(&'a self, request: &'a Request<'r>, response: &'a mut Response<'r>)
-> std::pin::Pin<Box<dyn std::future::Future<Output=()> + Send + 'a>>
{
Box::pin(async move {
if response.status() != Status::NotFound { if response.status() != Status::NotFound {
return return
} }
@ -49,6 +52,7 @@ impl Fairing for Counter {
response.set_header(ContentType::Plain); response.set_header(ContentType::Plain);
response.set_sized_body(Cursor::new(body)); response.set_sized_body(Cursor::new(body));
} }
})
} }
} }
@ -82,10 +86,12 @@ fn rocket() -> rocket::Rocket {
} }
})) }))
.attach(AdHoc::on_response("Response Rewriter", |req, res| { .attach(AdHoc::on_response("Response Rewriter", |req, res| {
Box::pin(async move {
if req.uri().path() == "/" { if req.uri().path() == "/" {
println!(" => Rewriting response body."); println!(" => Rewriting response body.");
res.set_sized_body(Cursor::new("Hello, fairings!")); res.set_sized_body(Cursor::new("Hello, fairings!"));
} }
})
})) }))
} }