From 05cf6b57c41887b623a56270dac5bc29064f465a Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Mon, 22 Aug 2016 20:40:19 -0700 Subject: [PATCH] Add the content_types example. --- examples/content_types/Cargo.toml | 12 ++++++++ examples/content_types/src/main.rs | 48 ++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 examples/content_types/Cargo.toml create mode 100644 examples/content_types/src/main.rs diff --git a/examples/content_types/Cargo.toml b/examples/content_types/Cargo.toml new file mode 100644 index 00000000..3ae49e9d --- /dev/null +++ b/examples/content_types/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "content_types" +version = "0.0.1" +authors = ["Sergio Benitez "] +workspace = "../../" + +[dependencies] +rocket = { path = "../../lib" } +rocket_macros = { path = "../../macros" } +serde = "0.8" +serde_json = "0.8" +serde_macros = "0.8" diff --git a/examples/content_types/src/main.rs b/examples/content_types/src/main.rs new file mode 100644 index 00000000..5cd33f1d --- /dev/null +++ b/examples/content_types/src/main.rs @@ -0,0 +1,48 @@ +#![feature(plugin, custom_derive)] +#![plugin(rocket_macros, serde_macros)] + +extern crate rocket; +extern crate serde_json; + +use rocket::{Rocket, RoutingError}; +use rocket::ContentType; +use rocket::Error; + +#[derive(Debug, Serialize, Deserialize)] +struct Person { + name: String, + age: i8, +} + +#[GET(path = "//", content = "application/json")] +fn hello(name: String, age: i8) -> String { + let person = Person { + name: name, + age: age, + }; + + serde_json::to_string(&person).unwrap() +} + +#[error(code = "404")] +fn not_found(error: RoutingError) -> String { + match error.error { + // Error::BadMethod if !error.request.content_type.is_json() => { + // format!("

This server only supports JSON requests, not '{}'.

", + // error.request.data) + // } + Error::BadMethod => { + format!("

Sorry, this server but '{}' is not a valid path!

+

Try visiting /hello/<name>/<age> instead.

", + error.request.uri) + } + _ => format!("

Bad Request

"), + } +} + +fn main() { + let mut rocket = Rocket::new("localhost", 8000); + rocket.mount("/hello", routes![hello]); + rocket.catch(errors![not_found]); + rocket.launch(); +}