feat: AppState struct

This commit is contained in:
Nathan McCarty 2023-07-26 02:44:38 -04:00
parent a689a064f4
commit 5d8521b646
Signed by: thatonelutenist
SSH Key Fingerprint: SHA256:3elIBybO7zXuCg+/os7OlO2fwfRPXmObQjcHXBf7Hfg
3 changed files with 21 additions and 6 deletions

View File

@ -1,15 +1,20 @@
use axum::{routing::get, Router}; 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] #[tokio::main]
async fn main() { async fn main() {
// Build our state
let shared_state = AppState {
title: "Stranger Systems".to_string(),
};
// build our application with a route // build our application with a route
let app = Router::new() let app = Router::new()
.route("/", get(index)) .route("/", get(index))
.route("/index", get(index)) .route("/index", get(index))
.route("/index.html", get(index)); .route("/index.html", get(index))
.with_state(Arc::new(shared_state));
// run it // run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

View File

@ -1 +1,6 @@
pub mod routes; pub mod routes;
/// Shared state for the application
pub struct AppState {
pub title: String,
}

View File

@ -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 /// Render the front page
pub async fn index() -> Html<String> { pub async fn index(State(state): State<Arc<AppState>>) -> Html<String> {
Html("<h1>Hello, World!</h1>".to_string()) let title: &str = state.title.as_ref();
Html(format!("<h1>Hello, World! Site Title: {title}</h1>"))
} }