achubb_website/src/lib.rs

103 lines
2.6 KiB
Rust
Raw Normal View History

use anyhow::Context;
use askama::Template;
use axum::{
response::IntoResponse,
routing::get,
Router,
};
use tower_http::services::ServeDir;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod html;
pub async fn run() -> anyhow::Result<()> {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "achubb_backend".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
info!("initializing router...");
let assets_path = std::env::current_dir().unwrap();
let port = 8000_u16;
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port));
let api_router = Router::new().route("/hello", get(hello_from_the_server));
let router = Router::new()
.nest("/api", api_router)
.route("/", get(home))
.route("/blog", get(blog))
.route("/projects", get(projects))
.route("/now", get(now))
.route("/about", get(about))
.route("/contact", get(contact))
.nest_service(
"/assets",
ServeDir::new(format!("{}/assets", assets_path.to_str().unwrap())),
);
info!("router initialized, now listening on port {}", port);
axum::Server::bind(&addr)
.serve(router.into_make_service())
.await
.context("error while starting server")?;
Ok(())
}
async fn home() -> impl IntoResponse {
let template = HomeTemplate {};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "home.html")]
struct HomeTemplate;
async fn blog() -> impl IntoResponse {
let template = BlogTemplate{};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "blog.html")]
struct BlogTemplate;
async fn projects() -> impl IntoResponse {
let template = ProjectsTemplate{};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "projects.html")]
struct ProjectsTemplate;
async fn now() -> impl IntoResponse {
let template = NowTemplate{};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "now.html")]
struct NowTemplate;
async fn about() -> impl IntoResponse {
let template = AboutTemplate{};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "about.html")]
struct AboutTemplate;
async fn contact() -> impl IntoResponse {
let template = ContactTemplate{};
html::HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "contact.html")]
struct ContactTemplate;
async fn hello_from_the_server() -> &'static str {
"Hello!"
}