contact-form/src/main.rs

84 lines
2 KiB
Rust
Raw Normal View History

2022-10-28 22:41:49 +00:00
mod captcha_solutions;
mod config;
2022-11-01 19:45:06 +00:00
mod errors;
2022-10-28 22:41:49 +00:00
mod forms;
mod logging;
2022-10-28 22:41:49 +00:00
mod mailer;
2022-10-26 00:23:55 +00:00
mod routes;
2022-12-03 16:08:23 +00:00
mod states;
2022-11-01 19:45:06 +00:00
mod templates;
2022-10-26 00:23:55 +00:00
2023-02-23 14:37:18 +00:00
use anyhow::{Context, Result};
2023-02-22 23:42:08 +00:00
use axum::{
routing::{get, get_service, Router},
Server,
};
use std::{env, net::SocketAddr, path::PathBuf, process};
2023-02-22 23:42:08 +00:00
use tower_http::services::ServeDir;
use tracing::{error, info};
2022-10-31 01:13:42 +00:00
use crate::{config::Config, states::AppState};
const DATA_DIR_ENV_VAR: &str = "CF_DATA_DIR";
async fn init(logger_initialized: &mut bool) -> Result<()> {
let data_dir = PathBuf::from(
env::var(DATA_DIR_ENV_VAR)
.with_context(|| format!("Environment variable {DATA_DIR_ENV_VAR} missing!"))?,
);
let config = Config::build(&data_dir)?;
logging::init_logger(&data_dir, &config.utc_offset)?;
*logger_initialized = true;
2023-02-24 00:19:07 +00:00
// The path prefix of all routes.
2023-02-25 17:08:21 +00:00
let path_prefix = config.state_config.path_prefix.clone();
let socket_address = config
2023-02-23 02:22:31 +00:00
.socket_address
.parse::<SocketAddr>()
2023-02-23 14:37:18 +00:00
.context("Failed to parse the socket address: {e:?}")?;
let app_state = AppState::build(config).await?;
2023-02-24 00:19:07 +00:00
// The service for serving the static files.
2023-02-25 20:25:45 +00:00
let static_service = get_service(ServeDir::new("static"));
2023-02-22 23:42:08 +00:00
2022-10-31 01:13:42 +00:00
let routes = Router::new()
2022-12-03 16:50:22 +00:00
.route("/", get(routes::index).post(routes::submit))
2023-02-22 23:42:08 +00:00
.with_state(app_state)
.nest_service("/static", static_service);
2022-12-03 16:15:49 +00:00
2023-02-26 13:07:24 +00:00
let app = {
2023-02-26 16:02:09 +00:00
if path_prefix.is_empty() {
2023-02-26 13:07:24 +00:00
// No need to nest.
routes
} else {
Router::new().nest(&path_prefix, routes)
}
};
2022-10-31 01:13:42 +00:00
2022-12-03 16:08:23 +00:00
info!("Starting server");
Server::bind(&socket_address)
2022-10-31 01:13:42 +00:00
.serve(app.into_make_service())
2023-02-23 14:37:18 +00:00
.await?;
2022-10-28 22:41:49 +00:00
2022-12-03 16:15:49 +00:00
Ok(())
2022-10-29 17:09:56 +00:00
}
/// Single thread.
2023-02-22 23:41:26 +00:00
#[tokio::main(flavor = "current_thread")]
2022-10-31 01:13:42 +00:00
async fn main() {
let mut logger_initialized = false;
if let Err(e) = init(&mut logger_initialized).await {
if logger_initialized {
error!("{e:?}");
} else {
eprintln!("{e:?}");
}
2022-10-29 17:09:56 +00:00
process::exit(1);
2023-01-12 19:55:56 +00:00
};
2022-10-26 00:23:55 +00:00
}