#![feature(proc_macro_hygiene, decl_macro)] pub mod models; pub mod schema; #[macro_use] extern crate rocket; #[macro_use] extern crate diesel; extern crate dotenv; extern crate rand; extern crate rocket_contrib; extern crate tera; use self::diesel::prelude::*; use self::models::*; use diesel::pg::PgConnection; use dotenv::dotenv; use rand::Rng; use rocket_contrib::serve::StaticFiles; use rocket_contrib::templates::Template; use std::env; use std::vec::Vec; use tera::Context; const TITLES: [&str; 4] = ["/* {} */", "# {}", "// {}", ""]; fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL not setted"); PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url)) } pub fn get_posts() -> Vec { use schema::posts::dsl::*; let connection = establish_connection(); posts .filter(published.eq(true)) .limit(20) .load::(&connection) .expect("Error loading posts") } #[get("/?")] fn index(page: Option) -> Template { let page = page.unwrap_or_else(|| 0); println!("{}", page); let mut context = Context::new(); let mut rng = rand::thread_rng(); let title_fmt = TITLES[rng.gen_range(0, TITLES.len())]; let title = str::replace(title_fmt, "{}", "CódigoComentado"); context.insert("title", &title); context.insert("posts", &get_posts()); Template::render("index", context) } fn main() { rocket::ignite() .attach(Template::fairing()) .mount("/", routes![index]) .mount("/static", StaticFiles::from("static")) .launch(); }