88 lines
1.9 KiB
Rust
88 lines
1.9 KiB
Rust
#![feature(proc_macro_hygiene, decl_macro)]
|
|
|
|
#[macro_use]
|
|
extern crate diesel;
|
|
|
|
use std::{collections::HashMap, net::SocketAddr};
|
|
|
|
use chrono::Local;
|
|
use diesel::SqliteConnection;
|
|
use log::{error, info};
|
|
use rocket::{
|
|
get, post,
|
|
request::{FlashMessage, Form},
|
|
response::{Flash, Redirect},
|
|
routes, uri, FromForm,
|
|
};
|
|
use rocket_contrib::{database, templates::Template};
|
|
|
|
mod models;
|
|
mod schema;
|
|
|
|
use models::NewPost;
|
|
|
|
#[database("sqlite")]
|
|
struct DbCon(SqliteConnection);
|
|
|
|
#[derive(FromForm)]
|
|
struct PostForm {
|
|
author: String,
|
|
email: String,
|
|
title: String,
|
|
content: String,
|
|
}
|
|
|
|
#[get("/create")]
|
|
fn create_form(flash: Option<FlashMessage>) -> Template {
|
|
let mut context = HashMap::new();
|
|
|
|
if let Some(ref msg) = flash {
|
|
context.insert("flash", msg.msg());
|
|
}
|
|
|
|
Template::render("create", &context)
|
|
}
|
|
|
|
#[post("/create", data = "<post>")]
|
|
fn create_post(
|
|
conn: DbCon,
|
|
remote_address: SocketAddr,
|
|
post: Form<PostForm>,
|
|
) -> Result<Redirect, Flash<Redirect>> {
|
|
let post = NewPost {
|
|
parent: None,
|
|
timestamp: Local::now().naive_local(),
|
|
author: &post.author.trim(),
|
|
email: &post.email.trim(),
|
|
title: &post.title.trim(),
|
|
content: &post.content.trim(),
|
|
};
|
|
|
|
match post.insert(&conn) {
|
|
Ok(_) => {
|
|
info!("New post from {}", remote_address);
|
|
Ok(Redirect::to(uri!(index)))
|
|
}
|
|
Err(e) => {
|
|
error!("Could not create post from {}: {:?}", remote_address, e);
|
|
Err(Flash::error(
|
|
Redirect::to(uri!(create_form)),
|
|
"Could not create post.".to_string(),
|
|
))
|
|
}
|
|
}
|
|
}
|
|
|
|
#[get("/")]
|
|
fn index() -> &'static str {
|
|
"Hello, world!"
|
|
}
|
|
|
|
fn main() {
|
|
rocket::ignite()
|
|
.mount("/", routes![index, create_form, create_post])
|
|
.attach(DbCon::fairing())
|
|
.attach(Template::fairing())
|
|
.launch();
|
|
}
|