2024-10-15 10:10:46 +00:00
|
|
|
use fully_pub::fully_pub;
|
2024-11-02 16:37:57 +00:00
|
|
|
use anyhow::{Result, Context};
|
2024-10-15 10:10:46 +00:00
|
|
|
use log::info;
|
|
|
|
use minijinja::{context, Environment};
|
|
|
|
use sqlx::{Pool, Sqlite};
|
2024-10-20 22:05:20 +00:00
|
|
|
use crate::{models::config::{AppSecrets, Config}, router::build_router};
|
2024-10-10 16:20:06 +00:00
|
|
|
|
2024-10-15 10:10:46 +00:00
|
|
|
fn build_templating_env(config: &Config) -> Environment<'static> {
|
2024-10-20 22:05:20 +00:00
|
|
|
let mut env = Environment::new();
|
2024-10-10 16:20:06 +00:00
|
|
|
|
2024-10-20 22:05:20 +00:00
|
|
|
minijinja_embed::load_templates!(&mut env);
|
2024-10-10 16:20:06 +00:00
|
|
|
|
2024-10-20 22:05:20 +00:00
|
|
|
env.add_global("gl", context! {
|
|
|
|
instance => config.instance
|
2024-10-10 16:20:06 +00:00
|
|
|
});
|
2024-10-20 22:05:20 +00:00
|
|
|
env
|
2024-10-10 16:20:06 +00:00
|
|
|
}
|
|
|
|
|
2024-10-15 10:10:46 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
#[fully_pub]
|
|
|
|
/// HTTP server arguments
|
|
|
|
pub struct ServerConfig {
|
|
|
|
listen_host: String,
|
|
|
|
listen_port: u32,
|
|
|
|
assets_path: String
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
#[fully_pub]
|
|
|
|
pub struct AppState {
|
2024-10-20 22:05:20 +00:00
|
|
|
secrets: AppSecrets,
|
2024-10-15 10:10:46 +00:00
|
|
|
config: Config,
|
|
|
|
db: Pool<Sqlite>,
|
|
|
|
templating_env: Environment<'static>
|
|
|
|
}
|
|
|
|
|
2024-10-20 22:05:20 +00:00
|
|
|
pub async fn start_http_server(
|
|
|
|
server_config: ServerConfig,
|
|
|
|
config: Config,
|
|
|
|
secrets: AppSecrets,
|
|
|
|
db_pool: Pool<Sqlite>
|
|
|
|
) -> Result<()> {
|
2024-10-15 10:10:46 +00:00
|
|
|
// build state
|
|
|
|
let state = AppState {
|
|
|
|
templating_env: build_templating_env(&config),
|
|
|
|
config,
|
2024-10-20 22:05:20 +00:00
|
|
|
secrets,
|
2024-10-15 10:10:46 +00:00
|
|
|
db: db_pool
|
|
|
|
};
|
|
|
|
|
|
|
|
// build routes
|
2024-10-20 22:05:20 +00:00
|
|
|
let services = build_router(
|
|
|
|
&server_config,
|
|
|
|
state.clone()
|
|
|
|
)
|
2024-10-15 10:10:46 +00:00
|
|
|
.with_state(state);
|
|
|
|
|
|
|
|
let listen_addr = format!("{}:{}", server_config.listen_host, server_config.listen_port);
|
|
|
|
info!("Starting web server on http://{}", &listen_addr);
|
|
|
|
let listener = tokio::net::TcpListener::bind(listen_addr).await.unwrap();
|
|
|
|
|
|
|
|
axum::serve(listener, services).await.context("Axum serve")?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|