rust_web_server/state/mod.rs
1//! Shared application state and state-aware routing.
2//!
3//! [`AppWithState<S>`] combines a typed state value (database pools, config,
4//! caches) with route registration. Routes are tried first; requests that do
5//! not match fall through to the built-in [`App`] controller chain (static
6//! files, healthz, metrics, …).
7//!
8//! State is stored as an [`Arc<S>`] and shared across all handlers. Handlers
9//! receive an immutable `&S` reference alongside the request context.
10//!
11//! # Example
12//!
13//! ```rust,no_run
14//! use rust_web_server::state::AppWithState;
15//! use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
16//! use rust_web_server::range::Range;
17//! use rust_web_server::mime_type::MimeType;
18//! use rust_web_server::core::New;
19//!
20//! struct AppState {
21//! greeting: String,
22//! }
23//!
24//! let app = AppWithState::new(AppState { greeting: "Hello".to_string() })
25//! .get("/greet", |_req, _params, _conn, state| {
26//! let mut r = Response::new();
27//! r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
28//! r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
29//! r.content_range_list = vec![
30//! Range::get_content_range(
31//! state.greeting.as_bytes().to_vec(),
32//! MimeType::TEXT_PLAIN.to_string(),
33//! )
34//! ];
35//! r
36//! })
37//! .get("/users/:id", |_req, params, _conn, state| {
38//! let id = params.get("id").unwrap_or("?");
39//! let body = format!("{}, user {}!", state.greeting, id);
40//! let mut r = Response::new();
41//! r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
42//! r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
43//! r.content_range_list = vec![
44//! Range::get_content_range(body.into_bytes(), MimeType::TEXT_PLAIN.to_string())
45//! ];
46//! r
47//! });
48//! ```
49
50#[cfg(test)]
51mod tests;
52
53use std::sync::Arc;
54
55use crate::app::App;
56use crate::application::Application;
57use crate::core::New;
58use crate::request::Request;
59use crate::response::Response;
60use crate::router::{PathParams, Router};
61use crate::server::ConnectionInfo;
62
63/// An [`Application`] that combines user-defined state-aware routes with the
64/// built-in [`App`] controller chain as a fallback.
65///
66/// Routes are matched in registration order. The first match wins; unmatched
67/// requests are forwarded to [`App`] (static files, health probes, etc.).
68pub struct AppWithState<S> {
69 state: Arc<S>,
70 router: Router,
71}
72
73impl<S: Send + Sync + 'static> AppWithState<S> {
74 /// Create a new `AppWithState` wrapping `state`.
75 ///
76 /// `state` is stored behind an `Arc` so it can be shared across threads
77 /// without cloning. Register routes with the builder methods.
78 pub fn new(state: S) -> Self {
79 AppWithState {
80 state: Arc::new(state),
81 router: Router::new(),
82 }
83 }
84
85 /// Return a reference to the shared state.
86 pub fn state(&self) -> &S {
87 &self.state
88 }
89
90 /// Register a `GET` handler for `pattern`.
91 pub fn get<F>(mut self, pattern: &str, handler: F) -> Self
92 where
93 F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
94 {
95 let state = Arc::clone(&self.state);
96 self.router = self.router.get(pattern, move |req, params, conn| {
97 handler(req, params, conn, &state)
98 });
99 self
100 }
101
102 /// Register a `POST` handler for `pattern`.
103 pub fn post<F>(mut self, pattern: &str, handler: F) -> Self
104 where
105 F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
106 {
107 let state = Arc::clone(&self.state);
108 self.router = self.router.post(pattern, move |req, params, conn| {
109 handler(req, params, conn, &state)
110 });
111 self
112 }
113
114 /// Register a `PUT` handler for `pattern`.
115 pub fn put<F>(mut self, pattern: &str, handler: F) -> Self
116 where
117 F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
118 {
119 let state = Arc::clone(&self.state);
120 self.router = self.router.put(pattern, move |req, params, conn| {
121 handler(req, params, conn, &state)
122 });
123 self
124 }
125
126 /// Register a `PATCH` handler for `pattern`.
127 pub fn patch<F>(mut self, pattern: &str, handler: F) -> Self
128 where
129 F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
130 {
131 let state = Arc::clone(&self.state);
132 self.router = self.router.patch(pattern, move |req, params, conn| {
133 handler(req, params, conn, &state)
134 });
135 self
136 }
137
138 /// Register a `DELETE` handler for `pattern`.
139 pub fn delete<F>(mut self, pattern: &str, handler: F) -> Self
140 where
141 F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
142 {
143 let state = Arc::clone(&self.state);
144 self.router = self.router.delete(pattern, move |req, params, conn| {
145 handler(req, params, conn, &state)
146 });
147 self
148 }
149}
150
151impl<S: Send + Sync + 'static> Application for AppWithState<S> {
152 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
153 if let Some(response) = self.router.handle(request, connection) {
154 return Ok(response);
155 }
156 App::new().execute(request, connection)
157 }
158}