added 404 response if a post is not found
parent
ac70178423
commit
0203b88900
26
src/main.rs
26
src/main.rs
|
@ -17,6 +17,7 @@ use self::diesel::prelude::*;
|
|||
use self::models::*;
|
||||
use comrak::{markdown_to_html, ComrakOptions};
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::result::Error;
|
||||
use dotenv::dotenv;
|
||||
use rand::Rng;
|
||||
use rocket::Request;
|
||||
|
@ -87,13 +88,13 @@ fn index(page: Option<i8>) -> Template {
|
|||
Template::render("index", context)
|
||||
}
|
||||
|
||||
fn get_post(id_number: i32) -> Post {
|
||||
fn get_post(id_number: i32) -> Result<Post, Error> {
|
||||
use schema::posts::dsl::*;
|
||||
|
||||
let connection = establish_connection();
|
||||
let post = posts.find(id_number).first(&connection);
|
||||
|
||||
post.unwrap()
|
||||
post
|
||||
}
|
||||
|
||||
#[get("/post/<title>")]
|
||||
|
@ -107,13 +108,24 @@ fn show_post(title: String) -> Template {
|
|||
let title_fmt = TITLES[rng.gen_range(0, TITLES.len())];
|
||||
let title = str::replace(title_fmt, "{}", "CódigoComentado");
|
||||
|
||||
let mut post = get_post(id);
|
||||
let content = markdown_to_html(&post.content, &ComrakOptions::default());
|
||||
post.content = content;
|
||||
let post = get_post(id);
|
||||
|
||||
context.insert("title", &title);
|
||||
context.insert("post", &post);
|
||||
Template::render("post", context)
|
||||
|
||||
match post {
|
||||
Ok(mut p) => {
|
||||
let content = markdown_to_html(&p.content, &ComrakOptions::default());
|
||||
p.content = content;
|
||||
|
||||
context.insert("post", &p);
|
||||
Template::render("post", context)
|
||||
}
|
||||
Err(_e) => {
|
||||
let uri = format!("/post/{}", title_splited.join("-"));
|
||||
context.insert("url", &uri);
|
||||
Template::render("404", context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[catch(404)]
|
||||
|
|
Loading…
Reference in New Issue