diff --git a/Cargo.toml b/Cargo.toml index 3b5031ac..97ae1a1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ members = [ "examples/raw_upload", "examples/pastebin", "examples/state", + "examples/managed_queue", "examples/uuid", "examples/session", "examples/raw_sqlite", diff --git a/examples/managed_queue/Cargo.toml b/examples/managed_queue/Cargo.toml new file mode 100644 index 00000000..6b261f44 --- /dev/null +++ b/examples/managed_queue/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "managed_queue" +version = "0.0.1" +workspace = "../.." + +[dependencies] +crossbeam = "*" +rocket = { path = "../../lib" } +rocket_codegen = { path = "../../codegen" } + +[dev-dependencies] +rocket = { path = "../../lib", features = ["testing"] } diff --git a/examples/managed_queue/src/main.rs b/examples/managed_queue/src/main.rs new file mode 100644 index 00000000..9f350b64 --- /dev/null +++ b/examples/managed_queue/src/main.rs @@ -0,0 +1,68 @@ +#![feature(plugin, custom_derive)] +#![plugin(rocket_codegen)] + +extern crate crossbeam; +extern crate rocket; + +use crossbeam::sync::MsQueue; +use rocket::State; + +#[derive(FromForm, Debug)] +struct Event { + description: String +} + +struct LogChannel(MsQueue); + +#[get("/push?")] +fn push(event: Event, queue: State) -> &'static str { + queue.0.push(event); + "got it" +} + +#[get("/pop")] +fn pop(queue: State) -> String { + let e = queue.0.pop(); + e.description +} + +// Use with: curl http://:8000/test?foo=bar + +fn main() { + let q:MsQueue = MsQueue::new(); + + rocket::ignite() + .mount("/", routes![push,pop]) + .manage(LogChannel(q)) + .launch(); + +} + +#[cfg(test)] +mod test { + use super::rocket; + use rocket::testing::MockRequest; + use rocket::http::Status; + use rocket::http::Method::*; + use crossbeam::sync::MsQueue; + use std::{thread, time}; + use super::LogChannel; + use super::Event; + + #[test] + fn test_get() { + let q: MsQueue = MsQueue::new(); + let rocket = rocket::ignite().manage(LogChannel(q)).mount("/", routes![super::push, super::pop]); + let mut req = MockRequest::new(Get, "/push?description=test1"); + let response = req.dispatch_with(&rocket); + assert_eq!(response.status(), Status::Ok); + + let ten_millis = time::Duration::from_millis(10); + thread::sleep(ten_millis); + + let mut req = MockRequest::new(Get, "/pop"); + let mut response = req.dispatch_with(&rocket); + let body_str = response.body().and_then(|body| body.into_string()); + assert_eq!(body_str, Some("test1".to_string())); + } +} \ No newline at end of file