From 5d8521b646e9e98410c55e45401d568b290fc582 Mon Sep 17 00:00:00 2001 From: Nathan McCarty Date: Wed, 26 Jul 2023 02:44:38 -0400 Subject: [PATCH] feat: AppState struct --- src/bin/stranger-site-server.rs | 11 ++++++++--- src/lib.rs | 5 +++++ src/routes/index.rs | 11 ++++++++--- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/bin/stranger-site-server.rs b/src/bin/stranger-site-server.rs index 19ef87e..fed6a71 100644 --- a/src/bin/stranger-site-server.rs +++ b/src/bin/stranger-site-server.rs @@ -1,15 +1,20 @@ use axum::{routing::get, Router}; -use std::net::SocketAddr; +use std::{net::SocketAddr, sync::Arc}; -use stranger_site::routes::index::index; +use stranger_site::{routes::index::index, AppState}; #[tokio::main] async fn main() { + // Build our state + let shared_state = AppState { + title: "Stranger Systems".to_string(), + }; // build our application with a route let app = Router::new() .route("/", get(index)) .route("/index", get(index)) - .route("/index.html", get(index)); + .route("/index.html", get(index)) + .with_state(Arc::new(shared_state)); // run it let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); diff --git a/src/lib.rs b/src/lib.rs index 6a664ab..cdd2eff 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,6 @@ pub mod routes; + +/// Shared state for the application +pub struct AppState { + pub title: String, +} diff --git a/src/routes/index.rs b/src/routes/index.rs index 367689d..6c927e7 100644 --- a/src/routes/index.rs +++ b/src/routes/index.rs @@ -1,6 +1,11 @@ -use axum::response::Html; +use std::sync::Arc; + +use axum::{extract::State, response::Html}; + +use crate::AppState; /// Render the front page -pub async fn index() -> Html { - Html("

Hello, World!

".to_string()) +pub async fn index(State(state): State>) -> Html { + let title: &str = state.title.as_ref(); + Html(format!("

Hello, World! Site Title: {title}

")) }