Echo Writes Code

web_pylon.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
mod configuration;
mod content;
mod errors;
mod handlers;
mod state;
mod templates;

use crate::content::{ ContentProvider };
use crate::errors::{ Result };
use crate::state::{ ApplicationState };

use axum::{ Router, serve };
use axum::routing::{ get };
use tera::{ Tera };
use tokio::net::{ TcpListener };
use tower_http::services::{ ServeDir };
use tower_http::trace::{ TraceLayer };

use std::process::{ ExitCode };
use std::sync::{ Arc };

#[tokio::main]
async fn main() -> ExitCode {
	let result = run_server().await;

	match result {
		Ok(_) => ExitCode::SUCCESS,
		Err(e) => {
			eprintln!("{}", e);
			ExitCode::FAILURE
		}
	}
}

async fn run_server() -> Result<()> {
	let configuration = configuration::configure()?;

	let state = ApplicationState {
		name: configuration.application_name.clone(),
		content_provider: ContentProvider::new(&configuration.content_root)?,
		tera: Tera::new("templates/**/*.tera.html")?,
	};

	let router = Router::new()
		.layer(TraceLayer::new_for_http())
		.route("/", get(handlers::index_handler))
		.route("/*path", get(handlers::page_handler))
		.nest_service("/content", ServeDir::new(&configuration.content_root))
		.nest_service("/static", ServeDir::new("static"))
		.fallback(handlers::not_found_handler)
		.with_state(Arc::new(state));

	let address = format!("{}:{}", configuration.network_host, configuration.network_port);
	let listener = TcpListener::bind(address).await?;
	tracing::debug!("web-pylon v{} now listening on {}", env!("CARGO_PKG_VERSION"), listener.local_addr()?);

	serve(listener, router).await?;
	Ok(())
}