Rocket/examples/fairings/src/main.rs

93 lines
2.7 KiB
Rust
Raw Normal View History

#[macro_use] extern crate rocket;
use std::io::Cursor;
2017-05-15 04:46:01 +00:00
use std::sync::atomic::{AtomicUsize, Ordering};
2021-03-10 05:13:26 +00:00
use std::sync::Arc;
use rocket::{Rocket, Request, State, Data};
2017-05-15 04:46:01 +00:00
use rocket::fairing::{AdHoc, Fairing, Info, Kind};
use rocket::http::Method;
struct Token(i64);
#[cfg(test)] mod tests;
2021-03-10 05:13:26 +00:00
#[derive(Default, Clone)]
2017-05-15 04:46:01 +00:00
struct Counter {
2021-03-10 05:13:26 +00:00
get: Arc<AtomicUsize>,
post: Arc<AtomicUsize>,
2017-05-15 04:46:01 +00:00
}
#[rocket::async_trait]
2017-05-15 04:46:01 +00:00
impl Fairing for Counter {
fn info(&self) -> Info {
Info {
name: "GET/POST Counter",
2021-03-10 05:13:26 +00:00
kind: Kind::Attach | Kind::Request
2017-05-15 04:46:01 +00:00
}
}
async fn on_request(&self, request: &mut Request<'_>, _: &mut Data) {
if request.method() == Method::Get {
self.get.fetch_add(1, Ordering::Relaxed);
} else if request.method() == Method::Post {
self.post.fetch_add(1, Ordering::Relaxed);
}
2017-05-15 04:46:01 +00:00
}
2021-03-10 05:13:26 +00:00
async fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
#[get("/counts")]
fn counts(counts: State<'_, Counter>) -> String {
let get_count = counts.get.load(Ordering::Relaxed);
let post_count = counts.post.load(Ordering::Relaxed);
format!("Get: {}\nPost: {}", get_count, post_count)
}
2017-05-15 04:46:01 +00:00
2021-03-10 05:13:26 +00:00
Ok(rocket.manage(self.clone()).mount("/", routes![counts]))
2017-05-15 04:46:01 +00:00
}
}
#[put("/")]
fn hello() -> &'static str {
"Hello, world!"
}
#[get("/token")]
2019-06-13 02:41:29 +00:00
fn token(token: State<'_, Token>) -> String {
format!("{}", token.0)
}
#[launch]
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![hello, token])
2017-05-15 04:46:01 +00:00
.attach(Counter::default())
.attach(AdHoc::on_attach("Token State", |rocket| async {
println!("Adding token managed state...");
match rocket.figment().extract_inner("token") {
Revamp configuration. This commit completely overhauls Rocket's configuration systems, basing it on the new Figment library. It includes many breaking changes pertaining to configuration. They are: * "Environments" are replaced by "profiles". * 'ROCKET_PROFILE' takes the place of 'ROCKET_ENV'. * Profile names are now arbitrary, but 'debug' and 'release' are given special treatment as default profiles for the debug and release compilation profiles. * A 'default' profile now sits along-side the meta 'global' profile. * The concept of "extras" is no longer present; users can extract any values they want from the configured 'Figment'. * The 'Poolable' trait takes an '&Config'. * The 'secrets' feature is disabled by default. * It is a hard error if 'secrets' is enabled under the 'release' profile and no 'secret_key' is configured. * 'ConfigBuilder' no longer exists: all fields of 'Config' are public with public constructors for each type. * 'keep_alive' is disabled with '0', not 'false' or 'off'. * Inlined error variants into the 'Error' structure. * 'LoggingLevel' is now 'LogLevel'. * Limits can now be specified in SI units: "1 MiB". The summary of other changes are: * The default config file can be configured with 'ROCKET_CONFIG'. * HTTP/1 and HTTP/2 keep-alive configuration is restored. * 'ctrlc' is now a recognized config option. * 'serde' is now a core dependency. * TLS misconfiguration errors are improved. * Several example use '_' as the return type of '#[launch]' fns. * 'AdHoc::config()' was added for simple config extraction. * Added more documentation for using 'Limits'. * Launch information is no longer treated specially. * The configuration guide was rewritten. Resolves #852. Resolves #209. Closes #1404. Closes #652.
2020-09-03 05:41:31 +00:00
Ok(value) => Ok(rocket.manage(Token(value))),
Err(_) => Err(rocket)
}
}))
.attach(AdHoc::on_launch("Launch Message", |_| {
println!("Rocket is about to launch!");
2017-05-15 04:46:01 +00:00
}))
.attach(AdHoc::on_request("PUT Rewriter", |req, _| {
Box::pin(async move {
println!(" => Incoming request: {}", req);
if req.uri().path() == "/" {
println!(" => Changing method to `PUT`.");
req.set_method(Method::Put);
}
})
2017-05-15 04:46:01 +00:00
}))
.attach(AdHoc::on_response("Response Rewriter", |req, res| {
2019-08-04 22:36:55 +00:00
Box::pin(async move {
if req.uri().path() == "/" {
println!(" => Rewriting response body.");
res.set_sized_body(None, Cursor::new("Hello, fairings!"));
2019-08-04 22:36:55 +00:00
}
})
2017-05-15 04:46:01 +00:00
}))
}