1
0
Fork 0
This repository has been archived on 2023-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
fedihub-website/src/main.rs

83 lines
1.9 KiB
Rust
Raw Normal View History

2020-10-14 20:36:24 +00:00
#![feature(decl_macro, proc_macro_hygiene)]
2020-10-13 23:40:03 +00:00
#[macro_use] extern crate rocket;
2020-10-14 00:13:00 +00:00
#[macro_use] extern crate serde_derive;
2020-10-14 20:27:21 +00:00
2020-10-14 21:12:13 +00:00
extern crate diesel;
extern crate dotenv;
2020-10-14 00:13:00 +00:00
extern crate rocket_contrib;
2020-10-13 23:40:03 +00:00
2020-10-14 21:12:13 +00:00
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use r2d2::{Pool, PooledConnection};
use rocket::{Outcome, Request, State};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
2020-10-14 00:01:25 +00:00
use rocket_contrib::templates::Template;
2020-10-14 21:12:13 +00:00
use std::env;
use std::ops::Deref;
struct DbConn(PooledConnection<ConnectionManager<PgConnection>>);
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<DbConn, ()> {
let pool =
request.guard::<State<Pool<ConnectionManager<PgConnection>>>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
impl Deref for DbConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}
2020-10-14 00:01:25 +00:00
2020-10-14 00:13:00 +00:00
#[derive(Serialize)]
struct TemplateContext {
parent: &'static str,
2020-10-14 00:22:37 +00:00
users: Vec<&'static str>,
2020-10-14 00:13:00 +00:00
}
2020-10-14 00:26:03 +00:00
fn main() {
2020-10-14 21:12:13 +00:00
dotenv::dotenv().ok();
2020-10-14 00:27:00 +00:00
rocket().launch();
}
fn rocket() -> rocket::Rocket {
2020-10-14 00:26:03 +00:00
rocket::ignite()
.attach(Template::fairing())
2020-10-14 00:29:50 +00:00
.mount("/", routes())
}
fn routes() -> Vec<rocket::Route> {
routes![index]
2020-10-14 00:26:03 +00:00
}
2020-10-14 21:12:13 +00:00
fn create_db_pool() -> Pool<ConnectionManager<PgConnection>> {
let credentials = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(credentials);
Pool::new(manager).expect("Failed to create database pool")
}
2020-10-13 23:40:03 +00:00
#[get("/")]
2020-10-14 00:01:25 +00:00
fn index() -> Template {
2020-10-14 00:13:00 +00:00
let template_context = TemplateContext {
parent: "layout",
2020-10-14 00:22:37 +00:00
users: vec!["foo", "bar", "car"],
2020-10-14 00:13:00 +00:00
};
Template::render("index", &template_context)
2020-10-13 23:40:03 +00:00
}