76 lines
2.4 KiB
Rust
76 lines
2.4 KiB
Rust
use actix_files::NamedFile;
|
|
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
|
|
use actix_web::{cookie::Key, middleware::Logger, web, App, HttpResponse, HttpServer};
|
|
use db::Database;
|
|
use std::env;
|
|
|
|
mod controller;
|
|
mod db;
|
|
|
|
#[actix_web::main]
|
|
async fn main() -> std::io::Result<()> {
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
|
dotenvy::dotenv().ok();
|
|
|
|
let database_url = build_database_url();
|
|
|
|
let database = Database::new(database_url.into()).await.unwrap();
|
|
|
|
let redis_conn = connect_to_redis_database().await;
|
|
|
|
// use dotenvy here to get SECRET_KEY
|
|
let secret_key = Key::generate();
|
|
println!("Secret Key {:?}", secret_key.master());
|
|
|
|
HttpServer::new(move || {
|
|
let app = App::new()
|
|
.app_data(web::Data::new(database.clone()))
|
|
.wrap(Logger::default())
|
|
.wrap(SessionMiddleware::new(
|
|
redis_conn.clone(),
|
|
secret_key.clone(),
|
|
))
|
|
.configure(controller::register_controllers);
|
|
|
|
#[cfg(feature = "serve")]
|
|
let app = {
|
|
println!("running serve");
|
|
app.default_service(
|
|
web::get().to(async || NamedFile::open_async("./web/index.html").await),
|
|
)
|
|
};
|
|
|
|
app
|
|
})
|
|
.bind(("0.0.0.0", 8080))?
|
|
.run()
|
|
.await
|
|
}
|
|
|
|
async fn connect_to_redis_database() -> RedisSessionStore {
|
|
let redis_host = dotenvy::var("REDIS_HOST").expect("REDIS_HOST must be set in .env");
|
|
let redis_port = dotenvy::var("REDIS_PORT")
|
|
.map(|x| x.parse::<u16>().expect("REDIS_PORT is not a valid port"))
|
|
.unwrap_or(6379);
|
|
let redis_connection_string = format!("redis://{}:{}", redis_host, redis_port);
|
|
let store = RedisSessionStore::new(redis_connection_string)
|
|
.await
|
|
.unwrap();
|
|
|
|
return store;
|
|
}
|
|
|
|
fn build_database_url() -> String {
|
|
let db_user = dotenvy::var("DB_USER").unwrap_or("pgg".to_owned());
|
|
let db_name = dotenvy::var("DB_NAME").unwrap_or("pgg".to_owned());
|
|
let db_password = dotenvy::var("DB_PASSWORD").unwrap_or("pgg".to_owned());
|
|
let db_host = dotenvy::var("DB_HOST").expect("DB_HOST must be set in .env");
|
|
let db_port = dotenvy::var("DB_PORT")
|
|
.map(|x| x.parse::<u16>().expect("DB_PORT is not a valid port"))
|
|
.unwrap_or(5432);
|
|
|
|
format!(
|
|
"postgresql://{}:{}@{}:{}/{}",
|
|
db_user, db_password, db_host, db_port, db_name
|
|
)
|
|
}
|