app/src/main.rs

79 lines
2.2 KiB
Rust
Raw Normal View History

use actix_web::{get, web, App, HttpResponse, HttpServer};
use rust_embed::RustEmbed;
2022-02-03 21:55:10 +00:00
use sea_orm::{Database, DatabaseConnection};
use tracing::{info, instrument};
2022-02-03 21:55:10 +00:00
use tracing_subscriber::prelude::*;
mod api;
mod auth;
2022-02-03 21:55:10 +00:00
mod entity;
mod error;
2022-02-03 21:55:10 +00:00
2022-02-11 21:23:31 +00:00
#[cfg(all(target_env = "musl", target_pointer_width = "64"))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
2022-02-03 21:55:10 +00:00
#[derive(Debug)]
pub struct AppState {
pub db: DatabaseConnection,
}
#[actix_web::main]
async fn main() {
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::Layer::new()
.pretty()
.with_writer(std::io::stdout)
.with_ansi(true)
2022-02-11 21:23:31 +00:00
.with_filter(tracing_subscriber::filter::LevelFilter::TRACE),
2022-02-03 21:55:10 +00:00
);
tracing::subscriber::set_global_default(subscriber).expect("Unable to set a global collector");
let db = setup_database().await.unwrap();
let state = web::Data::new(AppState { db });
2022-02-03 21:55:10 +00:00
info!("Starting http server on 8080");
HttpServer::new(move || {
App::new()
.app_data(state.clone())
2022-02-11 21:23:31 +00:00
.wrap(tracing_actix_web::TracingLogger::default())
.service(api::routes())
.service(dist)
})
2022-02-11 21:23:31 +00:00
.bind("0.0.0.0:8080")
.unwrap()
.run()
.await
.expect("Couldnt launch server");
}
#[derive(RustEmbed)]
#[folder = "dist"]
struct UIAssets;
#[get("/{filename:.*}")]
async fn dist(path: web::Path<String>) -> HttpResponse {
let path = if UIAssets::get(&*path).is_some() {
&*path
} else {
"index.html"
};
let content = UIAssets::get(path).unwrap();
let body: actix_web::body::BoxBody = match content {
std::borrow::Cow::Borrowed(bytes) => actix_web::body::BoxBody::new(bytes),
std::borrow::Cow::Owned(bytes) => actix_web::body::BoxBody::new(bytes),
};
HttpResponse::Ok()
.content_type(mime_guess::from_path(path).first_or_octet_stream().as_ref())
.body(body)
2022-02-03 21:55:10 +00:00
}
#[instrument]
2022-02-11 21:23:31 +00:00
async fn setup_database() -> error::Result<DatabaseConnection> {
let pool = sqlx::SqlitePool::connect("sqlite://data.db").await?;
sqlx::migrate!("./migrations").run(&pool).await?;
tracing::info!("Database migrated");
Ok(Database::connect("sqlite://data.db").await?)
2022-02-03 21:55:10 +00:00
}