#![feature(plugin)] #![plugin(rocket_codegen)] extern crate diesel; extern crate rocket; extern crate rocket_blog; extern crate rocket_contrib; #[macro_use] extern crate bart_derive; #[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, 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, _: &Request) -> Result, Status> { Response::build() .header(ContentType::HTML) .sized_body(Cursor::new(format!("{}", &self))) .ok() } } impl<'a> Responder<'a> for posts::NewPostTemplate<'a> { fn respond_to(self, _: &Request) -> Result, Status> { Response::build() .header(ContentType::HTML) .sized_body(Cursor::new(format!("{}", &self))) .ok() } } fn get_posts(conn: rocket_blog::DbConn) -> Vec { use schema::posts::dsl::*; posts.filter(published.eq(false)) .limit(5) .load::(&*conn) .expect("Error loading posts") } #[get("/", format = "text/html")] fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> { IndexTemplate { title: "Bloggen", posts: get_posts(conn) } } #[get("/", format = "application/json")] fn index_json(conn: rocket_blog::DbConn) -> Json> { Json(get_posts(conn)) } mod posts { use rocket::request::Form; use rocket::response::Redirect; use diesel::{self, ExecuteDsl}; #[derive(BartDisplay)] #[template = "templates/new_post.html"] pub struct NewPostTemplate<'a> { title: &'a str, post: ::models::NewPost } #[get("/new", format = "text/html")] fn new<'a>(_conn: ::rocket_blog::DbConn) -> NewPostTemplate<'a> { NewPostTemplate { title: "Bloggen", post: Default::default() } } #[post("/create", data="")] fn create(post: Form<::models::NewPost>, conn: ::rocket_blog::DbConn) -> Redirect { use ::schema::posts; diesel::insert(post.get()) .into(posts::table) .execute(&*conn) .expect("Error saving post."); Redirect::to("/") } } fn main() { rocket::ignite() .manage(rocket_blog::init_db_pool()) .mount("/", routes![index, index_json]) .mount("/posts", routes![posts::new, posts::create]) .launch(); }