codigocomentado/src/main.rs

69 lines
1.7 KiB
Rust
Raw Normal View History

2019-11-13 07:17:38 +00:00
#![feature(proc_macro_hygiene, decl_macro)]
2019-11-14 02:10:42 +00:00
pub mod models;
pub mod schema;
2019-11-13 07:17:38 +00:00
#[macro_use]
extern crate rocket;
2019-11-14 02:10:42 +00:00
#[macro_use]
extern crate diesel;
extern crate dotenv;
2019-11-13 07:17:38 +00:00
extern crate rand;
extern crate rocket_contrib;
2019-11-14 02:10:42 +00:00
extern crate tera;
2019-11-13 07:17:38 +00:00
2019-11-14 02:10:42 +00:00
use self::diesel::prelude::*;
use self::models::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
2019-11-13 07:17:38 +00:00
use rand::Rng;
use rocket_contrib::serve::StaticFiles;
use rocket_contrib::templates::Template;
2019-11-14 02:10:42 +00:00
use std::env;
use std::vec::Vec;
use tera::Context;
2019-11-13 07:17:38 +00:00
const TITLES: [&str; 4] = ["/* {} */", "# {}", "// {}", "<!-- {} -->"];
2019-11-14 02:10:42 +00:00
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<Post> {
use schema::posts::dsl::*;
let connection = establish_connection();
posts
.filter(published.eq(true))
.limit(20)
.load::<Post>(&connection)
.expect("Error loading posts")
}
#[get("/?<page>")]
fn index(page: Option<i8>) -> Template {
let page = page.unwrap_or_else(|| 0);
println!("{}", page);
let mut context = Context::new();
2019-11-13 07:17:38 +00:00
let mut rng = rand::thread_rng();
let title_fmt = TITLES[rng.gen_range(0, TITLES.len())];
let title = str::replace(title_fmt, "{}", "CódigoComentado");
2019-11-14 02:10:42 +00:00
context.insert("title", &title);
context.insert("posts", &get_posts());
2019-11-13 07:17:38 +00:00
Template::render("index", context)
}
2019-11-13 01:57:32 +00:00
fn main() {
2019-11-13 07:17:38 +00:00
rocket::ignite()
.attach(Template::fairing())
.mount("/", routes![index])
.mount("/static", StaticFiles::from("static"))
.launch();
2019-11-13 01:57:32 +00:00
}