From c65b9e00d5d37722e7e4887e7165e19931048c83 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Mon, 20 Nov 2017 20:53:00 +0100 Subject: Use route decorators to produce different output formats. This seems to be the more proper way of doing it. Also makes it much clearer which routes exists, and what formats they accept. Both in the code and in the status output. --- Cargo.toml | 5 +++++ src/main.rs | 43 +++++++++++++++++++++---------------------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7202391..762ce89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,8 @@ bart_derive = "0.1.4" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" + +[dependencies.rocket_contrib] +version = "0.3.3" +default-features = false +features = ["json"] diff --git a/src/main.rs b/src/main.rs index 1794722..1d20cb0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,16 +4,16 @@ extern crate diesel; extern crate rocket; extern crate rocket_blog; +extern crate rocket_contrib; #[macro_use] extern crate bart_derive; -extern crate serde; -extern crate serde_json; #[macro_use] extern crate serde_derive; use self::diesel::prelude::*; use self::rocket_blog::{schema, models}; +use rocket_contrib::Json; use rocket::response::{Response, Responder}; use rocket::request::Request; -use rocket::http::{ContentType, MediaType, Status}; +use rocket::http::{ContentType, Status}; use std::io::Cursor; #[derive(BartDisplay, Serialize)] @@ -24,36 +24,35 @@ struct IndexTemplate<'a> { } impl<'a> Responder<'a> for IndexTemplate<'a> { - fn respond_to(self, req: &Request) -> Result, Status> { - if req.format().unwrap().is_json() { - Response::build() - .header(ContentType::JSON) - .sized_body(Cursor::new(format!("{}", serde_json::to_string(&self).unwrap()))) - .ok() - } - else { - Response::build() - .header(ContentType::HTML) - .sized_body(Cursor::new(format!("{}", &self))) - .ok() - } + fn respond_to(self, _: &Request) -> Result, Status> { + Response::build() + .header(ContentType::HTML) + .sized_body(Cursor::new(format!("{}", &self))) + .ok() } } -#[get("/")] -fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> { +fn get_posts(conn: rocket_blog::DbConn) -> Vec { use schema::posts::dsl::*; - let results = posts.filter(published.eq(false)) + posts.filter(published.eq(false)) .limit(5) .load::(&*conn) - .expect("Error loading posts"); + .expect("Error loading posts") +} + +#[get("/", format = "text/html")] +fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> { + IndexTemplate { title: "Bloggen", posts: get_posts(conn) } +} - IndexTemplate { title: "Bloggen", posts: results } +#[get("/", format = "application/json")] +fn index_json(conn: rocket_blog::DbConn) -> Json> { + Json(get_posts(conn)) } fn main() { rocket::ignite() .manage(rocket_blog::init_db_pool()) - .mount("/", routes![index]) + .mount("/", routes![index, index_json]) .launch(); } -- cgit v1.2.3