Skip to content

Commit

Permalink
Handle 404s
Browse files Browse the repository at this point in the history
  • Loading branch information
Celeo committed Feb 25, 2024
1 parent 0292ae2 commit 966d49c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 13 deletions.
25 changes: 13 additions & 12 deletions src/endpoints.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
//! HTTP endpoints.
use crate::shared::AppState;
use crate::shared::{AppState, UserInfo, SESSION_USER_INFO_KEY};
use anyhow::Result;
use axum::{extract::State, http::StatusCode, response::Html};
use minijinja::context;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower_sessions::Session;

#[derive(Serialize, Deserialize, Default)]
struct Counter(usize);
pub async fn handler_404(
State(state): State<Arc<AppState>>,
session: Session,
) -> Result<Html<String>, StatusCode> {
let user_info: Option<UserInfo> = session.get(SESSION_USER_INFO_KEY).await.unwrap();
let template = state.templates.get_template("404").unwrap();
let rendered = template.render(context! { user_info }).unwrap();

Ok(Html(rendered))
}

pub async fn handler_home(
State(state): State<Arc<AppState>>,
session: Session,
) -> Result<Html<String>, StatusCode> {
let counter: Counter = session.get("COUNTER").await.unwrap().unwrap_or_default();
let user_info: Option<UserInfo> = session.get(SESSION_USER_INFO_KEY).await.unwrap();
let template = state.templates.get_template("home").unwrap();
let rendered = template
.render(context! {
title => "Home",
welcome_text => "Hello World!",
counter => counter,
})
.unwrap();
let rendered = template.render(context! { user_info }).unwrap();

Ok(Html(rendered))
}
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use crate::shared::{AppState, Config};
use anyhow::Result;
use axum::{middleware as axum_middleware, routing::get, Router};
use axum::{middleware as axum_middleware, response::Redirect, routing::get, Router};
use clap::Parser;
use log::{debug, error, info};
use minijinja::Environment;
Expand All @@ -13,9 +13,11 @@ use std::{
env,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use tokio::signal;
use tower::ServiceBuilder;
use tower_http::timeout::TimeoutLayer;
use tower_sessions::SessionManagerLayer;
use tower_sessions_sqlx_store::SqliteStore;

Expand Down Expand Up @@ -62,6 +64,8 @@ fn load_templates() -> Environment<'static> {
.unwrap();
env.add_template("home", include_str!("../templates/home.jinja"))
.unwrap();
env.add_template("404", include_str!("../templates/404.jinja"))
.unwrap();
env
}

Expand All @@ -87,12 +91,15 @@ fn load_router(
sessions_layer: SessionManagerLayer<SqliteStore>,
) -> Router {
Router::new()
.route("/404", get(endpoints::handler_404))
.route("/", get(endpoints::handler_home))
.layer(
ServiceBuilder::new()
.layer(TimeoutLayer::new(Duration::from_secs(30)))
.layer(axum_middleware::from_fn(middleware::logging))
.layer(sessions_layer),
)
.fallback(|| async { Redirect::to("/404") })
.with_state(app_state)
}

Expand Down
11 changes: 11 additions & 0 deletions templates/404.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!-- prettier-ignore -->
{% extends "layout" %}

{% block title %}Not found | {{ super() }}{% endblock %}

<!-- prettier-ignore -->
{% block body %}

<h1>Something went wrong</h1>
<h4>That page couldn't be found.</h4>
{% endblock %}

0 comments on commit 966d49c

Please sign in to comment.