#![feature(plugin)] #![plugin(rocket_codegen)] extern crate diesel; extern crate rocket; extern crate rocket_blog; #[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::response::{Response, Responder}; use rocket::request::Request; use rocket::http::{ContentType, MediaType, Status}; use std::io::Cursor; #[derive(BartDisplay, Serialize)] #[template = "templates/index.html"] struct IndexTemplate<'a> { title: &'a str, posts: Vec } 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() } } } #[get("/")] fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> { use schema::posts::dsl::*; let results = posts.filter(published.eq(false)) .limit(5) .load::(&*conn) .expect("Error loading posts"); IndexTemplate { title: "Bloggen", posts: results } } fn main() { rocket::ignite() .manage(rocket_blog::init_db_pool()) .mount("/", routes![index]) .launch(); }