replaced askama with tera, reworked the whole website and added nixos module
This commit is contained in:
@@ -1,19 +1,55 @@
|
||||
use askama::Template;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
extract::State,
|
||||
response::{Html, IntoResponse},
|
||||
};
|
||||
use serde::Serialize;
|
||||
use tera::Context;
|
||||
|
||||
pub async fn render_homepage() -> impl IntoResponse {
|
||||
#[derive(Template)]
|
||||
#[template(path = "homepage.html")]
|
||||
struct HomePageTemplate<'a> {
|
||||
lang: &'a str,
|
||||
}
|
||||
use crate::{AppState, TEMPLATES};
|
||||
|
||||
let tmpl = HomePageTemplate { lang: "en" };
|
||||
match tmpl.render() {
|
||||
/// Handler for the Home Page
|
||||
pub async fn home_handler(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let mut context = Context::new();
|
||||
context.insert("title", &state.app_name);
|
||||
context.insert("server_time", &chrono::Local::now().to_rfc2822());
|
||||
|
||||
match TEMPLATES.render("index.html", &context) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Template render error").into_response(),
|
||||
Err(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler for the Showcase Page
|
||||
pub async fn showcase_handler() -> impl IntoResponse {
|
||||
#[derive(Serialize)]
|
||||
struct ShowcaseItem {
|
||||
name: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
let mut context = Context::new();
|
||||
context.insert("title", "Showcase");
|
||||
|
||||
let items = vec![
|
||||
ShowcaseItem {
|
||||
name: "Project Alpha".into(),
|
||||
description: "A cool Rust project".into(),
|
||||
},
|
||||
ShowcaseItem {
|
||||
name: "Project Beta".into(),
|
||||
description: "An Axum powered API".into(),
|
||||
},
|
||||
ShowcaseItem {
|
||||
name: "Project Gamma".into(),
|
||||
description: "Tera template engine".into(),
|
||||
},
|
||||
];
|
||||
context.insert("items", &items);
|
||||
|
||||
match TEMPLATES.render("showcase.html", &context) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
59
src/lib.rs
59
src/lib.rs
@@ -1,59 +0,0 @@
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
http::{Method, header},
|
||||
routing::get,
|
||||
};
|
||||
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
|
||||
use crate::handlers::render_homepage;
|
||||
|
||||
pub mod handlers;
|
||||
|
||||
/// Start the server with the given configuration and output file.
|
||||
/// `addr` should be something like "127.0.0.1:8081"
|
||||
pub async fn run_server(addr: &str, verbose: bool) -> anyhow::Result<()> {
|
||||
// CORS
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods([Method::GET, Method::POST])
|
||||
.allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]);
|
||||
|
||||
// rate limiter
|
||||
let governor_conf = GovernorConfigBuilder::default()
|
||||
.per_second(3)
|
||||
.burst_size(10)
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
// a separate background task to clean up
|
||||
let governor_limiter = governor_conf.limiter().clone();
|
||||
let interval = Duration::from_secs(60);
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(interval);
|
||||
if verbose {
|
||||
tracing::info!("rate limiting storage size: {}", governor_limiter.len());
|
||||
}
|
||||
governor_limiter.retain_recent();
|
||||
}
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(render_homepage))
|
||||
.layer(cors)
|
||||
.layer(GovernorLayer::new(governor_conf));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
tracing::info!("Listening on {}", addr);
|
||||
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
57
src/main.rs
57
src/main.rs
@@ -1,26 +1,55 @@
|
||||
use clap::Parser;
|
||||
use axum::{Router, routing::get};
|
||||
use lazy_static::lazy_static;
|
||||
use std::sync::Arc;
|
||||
use tera::Tera;
|
||||
|
||||
use mycoolwebsite::run_server;
|
||||
mod handlers;
|
||||
use handlers::{home_handler, showcase_handler};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
struct Cli {
|
||||
#[arg(short, long)]
|
||||
verbose: bool,
|
||||
lazy_static! {
|
||||
pub static ref TEMPLATES: Tera = {
|
||||
let mut tera = Tera::default();
|
||||
tera.add_raw_templates(vec![
|
||||
("_layout.html", include_str!("../templates/_layout.html")),
|
||||
("_base.css", include_str!("../templates/_base.css")),
|
||||
("index.html", include_str!("../templates/homepage.html")),
|
||||
("showcase.html", include_str!("../templates/showcase.html")),
|
||||
])
|
||||
.unwrap();
|
||||
tera
|
||||
};
|
||||
}
|
||||
|
||||
struct AppState {
|
||||
app_name: String,
|
||||
}
|
||||
|
||||
/// Cli handler
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.init();
|
||||
|
||||
let subscriber = tracing_subscriber::FmtSubscriber::new();
|
||||
tracing::subscriber::set_global_default(subscriber).ok();
|
||||
let shared_state = Arc::new(AppState {
|
||||
app_name: "Quick rust website template".to_string(),
|
||||
});
|
||||
|
||||
let port = std::env::var("SERVER_PORT").unwrap_or("8081".to_string());
|
||||
let addr = format!("127.0.0.1:{port}");
|
||||
let app = Router::new()
|
||||
.route("/", get(home_handler))
|
||||
.route("/showcase", get(showcase_handler))
|
||||
.with_state(shared_state);
|
||||
|
||||
run_server(&addr, cli.verbose).await?;
|
||||
let host = false;
|
||||
let port = "8000";
|
||||
let addr = if host {
|
||||
format!("0.0.0.0:{}", port)
|
||||
} else {
|
||||
format!("127.0.0.1:{}", port)
|
||||
};
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||
tracing::info!("Listening on http://{}", addr);
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user