#![feature(plugin, custom_derive, custom_attribute)] #![plugin(rocket_codegen, serde_macros, diesel_codegen)] extern crate rocket; #[macro_use] extern crate diesel; #[macro_use] extern crate lazy_static; #[macro_use] extern crate rocket_contrib; extern crate serde_json; mod static_files; mod task; use rocket::Rocket; use rocket::response::{Flash, Redirect}; use rocket_contrib::Template; use task::Task; #[derive(Debug, Serialize)] struct Context<'a, 'b>{msg: Option<(&'a str, &'b str)>, tasks: Vec} impl<'a, 'b> Context<'a, 'b> { pub fn err(msg: &'a str) -> Context<'static, 'a> { Context{msg: Some(("error", msg)), tasks: Task::all()} } pub fn raw(msg: Option<(&'a str, &'b str)>) -> Context<'a, 'b> { Context{msg: msg, tasks: Task::all()} } } #[post("/", form = "")] fn new(todo: Task) -> Result, Template> { if todo.description.is_empty() { Err(Template::render("index", Context::err("Description cannot be empty."))) } else if todo.insert() { Ok(Flash::success(Redirect::to("/"), "Todo successfully added.")) } else { Err(Template::render("index", Context::err("Whoops! The server failed."))) } } // Should likely do something to simulate PUT. #[get("//toggle")] fn toggle(id: i32) -> Result { if Task::toggle_with_id(id) { Ok(Redirect::to("/")) } else { Err(Template::render("index", Context::err("Couldn't toggle task."))) } } // Should likely do something to simulate DELETE. #[get("//delete")] fn delete(id: i32) -> Result, Template> { if Task::delete_with_id(id) { Ok(Flash::success(Redirect::to("/"), "Todo was deleted.")) } else { Err(Template::render("index", Context::err("Couldn't delete task."))) } } #[get("/")] fn index(msg: Option>) -> Template { Template::render("index", match msg { Some(ref msg) => Context::raw(Some((msg.name(), msg.msg()))), None => Context::raw(None), }) } fn main() { let mut rocket = Rocket::new("127.0.0.1", 8000); rocket.mount("/", routes![index, static_files::all]) .mount("/todo/", routes![new, toggle, delete]); rocket.launch(); }