Skip to content

Commit

Permalink
feat: 404 page
Browse files Browse the repository at this point in the history
  • Loading branch information
Erb3 committed May 25, 2024
1 parent 67f2d5a commit 55e1ea2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
15 changes: 15 additions & 0 deletions frontend/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sveio - Page Not Found</title>
<link rel="stylesheet" href="/static/ui.css" />
</head>
<body>
<main class="flex flex-center flex-col">
<h1>404 - Not Found</h1>
<p>We were unable to locate this page. Go <a href="/">home</a>!</p>
</main>
</body>
</html>
23 changes: 20 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod datasource;
mod game;
mod utils;
use axum::handler::Handler;
use axum::http::{HeaderMap, Method};
use axum::response::IntoResponse;
use axum::routing::get;
Expand All @@ -21,13 +22,15 @@ fn read_file(path: &str) -> String {
struct AppState {
landing_page_content: String,
game_page_content: String,
not_found_page_content: String,
}

impl AppState {
fn get() -> AppState {
AppState {
landing_page_content: read_file("./frontend/landing.html"),
game_page_content: read_file("./frontend/game.html"),
not_found_page_content: read_file("./frontend/404.html"),
}
}
}
Expand All @@ -54,17 +57,23 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

io.ns("/", game::on_connect);

let state = AppState::get();
let app = axum::Router::new()
.route("/", get(landing_page))
.route("/game", get(game_page))
.with_state(AppState::get())
.nest_service("/static/", ServeDir::new("frontend"))
.nest_service(
"/static/",
ServeDir::new("frontend")
.not_found_service(Handler::with_state(get(not_found_page), state.clone())),
)
.layer(socketio_layer)
.fallback(get(not_found_page))
.layer(
CorsLayer::new()
.allow_methods([Method::GET])
.allow_origin(Any),
)
.layer(socketio_layer);
.with_state(state);

info!("🎮 Starting game loop");

Expand All @@ -86,6 +95,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

async fn not_found_page(
axum::extract::State(state): axum::extract::State<AppState>,
) -> impl IntoResponse {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "text/html; charset=utf-8".parse().unwrap());
(headers, state.not_found_page_content)
}

async fn landing_page(
axum::extract::State(state): axum::extract::State<AppState>,
) -> impl IntoResponse {
Expand Down

0 comments on commit 55e1ea2

Please sign in to comment.