Ad-Hoc Fairings

For simple occasions, implementing the Fairing trait can be cumbersome. This is why Rocket provides the AdHoc type, which creates a fairing from a simple function or closure. Using the AdHoc type is easy: simply call the on_attach, on_launch, on_request, or on_response constructors on AdHoc to create an AdHoc structure from a function or closure.

As an example, the code below creates a Rocket instance with two attached ad-hoc fairings. The first, a launch fairing, simply prints a message indicating that the application is about to the launch. The second, a request fairing, changes the method of all requests to PUT.

  1. use rocket::fairing::AdHoc;
  2. use rocket::http::Method;
  3. rocket::ignite()
  4. .attach(AdHoc::on_launch(|_| {
  5. println!("Rocket is about to launch! Exciting!");
  6. }))
  7. .attach(AdHoc::on_request(|req, _| {
  8. req.set_method(Method::Put);
  9. }));