Rocket/examples/fairings/src/main.rs

101 lines
2.9 KiB
Rust
Raw Normal View History

#![feature(proc_macro_hygiene, async_await)]
#[macro_use] extern crate rocket;
use std::io::Cursor;
2017-05-15 04:46:01 +00:00
use std::sync::atomic::{AtomicUsize, Ordering};
use rocket::{Request, State, Data, Response};
2017-05-15 04:46:01 +00:00
use rocket::fairing::{AdHoc, Fairing, Info, Kind};
use rocket::http::{Method, ContentType, Status};
struct Token(i64);
#[cfg(test)] mod tests;
2017-05-15 04:46:01 +00:00
#[derive(Default)]
struct Counter {
get: AtomicUsize,
post: AtomicUsize,
}
impl Fairing for Counter {
fn info(&self) -> Info {
Info {
name: "GET/POST Counter",
kind: Kind::Request | Kind::Response
}
}
2019-06-13 02:41:29 +00:00
fn on_request(&self, request: &mut Request<'_>, _: &Data) {
2017-05-15 04:46:01 +00:00
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);
}
}
2019-08-04 22:36:55 +00:00
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 {
return
}
2017-05-15 04:46:01 +00:00
2019-08-04 22:36:55 +00:00
if request.method() == Method::Get && request.uri().path() == "/counts" {
let get_count = self.get.load(Ordering::Relaxed);
let post_count = self.post.load(Ordering::Relaxed);
2017-05-15 04:46:01 +00:00
2019-08-04 22:36:55 +00:00
let body = format!("Get: {}\nPost: {}", get_count, post_count);
response.set_status(Status::Ok);
response.set_header(ContentType::Plain);
response.set_sized_body(Cursor::new(body));
}
})
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)
}
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| {
println!("Adding token managed state...");
let token_val = rocket.config().get_int("token").unwrap_or(-1);
Ok(rocket.manage(Token(token_val)))
}))
.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, _| {
println!(" => Incoming request: {}", req);
2017-05-15 04:46:01 +00:00
if req.uri().path() == "/" {
println!(" => Changing method to `PUT`.");
req.set_method(Method::Put);
}
}))
.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(Cursor::new("Hello, fairings!"));
}
})
2017-05-15 04:46:01 +00:00
}))
}
fn main() {
rocket().launch();
}