Rocket/examples/fairings/src/main.rs

85 lines
2.3 KiB
Rust
Raw Normal View History

#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
use std::io::Cursor;
2017-05-15 04:46:01 +00:00
use std::sync::atomic::{AtomicUsize, Ordering};
2017-05-15 04:46:01 +00:00
use rocket::{Request, Data, Response};
use rocket::fairing::{AdHoc, Fairing, Info, Kind};
use rocket::http::{Method, ContentType, Status};
#[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
}
}
fn on_request(&self, request: &mut Request, _: &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);
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
if response.status() != Status::NotFound {
return
}
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);
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));
}
}
}
#[put("/")]
fn hello() -> &'static str {
"Hello, world!"
}
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![hello])
2017-05-15 04:46:01 +00:00
.attach(Counter::default())
.attach(AdHoc::on_launch(|rocket| {
println!("Rocket is about to launch! Exciting! Here we go...");
Ok(rocket)
2017-05-15 04:46:01 +00:00
}))
.attach(AdHoc::on_request(|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(|req, res| {
if req.uri().path() == "/" {
println!(" => Rewriting response body.");
res.set_sized_body(Cursor::new("Hello, fairings!"));
}
}))
}
fn main() {
rocket().launch();
}