1use super::error::DefaultError;
2
3#[diagnostic::on_unimplemented(
32 message = "`{Self}` is not a web application state",
33 label = "does not implement `web::State`",
34 note = "implement `web::State` for `{Self}` with `type Error = web::DefaultError;`, or wrap it in `web::AppState<{Self}>`"
35)]
36pub trait State: 'static {
37 type Error;
39}
40
41impl State for () {
42 type Error = DefaultError;
43}
44
45#[derive(Clone, Default)]
68#[doc(alias = "Data")]
69pub struct AppState<T> {
70 state: T,
71}
72
73impl<T> AppState<T> {
74 pub fn new(state: T) -> Self {
76 AppState { state }
77 }
78
79 pub fn st(&self) -> &T {
81 &self.state
82 }
83}
84
85impl<T: 'static> State for AppState<T> {
86 type Error = DefaultError;
87}
88
89impl<T> std::ops::Deref for AppState<T> {
90 type Target = T;
91
92 fn deref(&self) -> &T {
93 &self.state
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use std::{cell::Cell, convert::Infallible, rc::Rc};
100
101 use super::*;
102 use crate::http::{Method, StatusCode};
103 use crate::service::ServiceFactory;
104 use crate::web::test::{TestRequest, init_service_st, read_body};
105 use crate::web::{self, App, HttpRequest, WebRequest, types::Path};
106
107 #[derive(Clone, Default)]
108 struct Counter {
109 name: &'static str,
110 hits: Rc<Cell<usize>>,
111 }
112
113 type St = AppState<Counter>;
114
115 async fn index(st: &St, (): ()) -> String {
116 st.hits.set(st.hits.get() + 1);
117 format!("index:{}", st.name)
118 }
119
120 async fn item(st: &St, (): (), id: Path<u32>) -> String {
121 format!("item:{}:{}", st.st().name, id.into_inner())
122 }
123
124 async fn fallback(st: &St, (): (), req: HttpRequest) -> String {
125 format!("fallback:{}:{}", st.name, req.method())
126 }
127
128 async fn filtered(_: &St, n: usize) -> String {
129 format!("filtered:{n}")
130 }
131
132 #[crate::rt_test]
139 async fn state_handlers() {
140 let st = AppState::new(Counter {
141 name: "app",
142 ..Counter::default()
143 });
144 let srv = init_service_st(
145 st.clone(),
146 App::<St>::new()
147 .service(web::resource("/index").to_with_state(index))
148 .service(web::resource("/item/{id}").to_with_state(item))
149 .service(
150 web::resource("/multi")
151 .route(web::get().to(async || "get"))
152 .route(web::delete().to_with_state(index))
153 .to(async || "any"),
154 )
155 .service(
156 web::resource("/fallback")
157 .route(web::get().to(async || "get"))
158 .to_with_state(fallback),
159 )
160 .service(
161 web::resource("/filtered")
162 .filter(async |req: WebRequest<()>| {
163 Ok::<_, Infallible>(req.map_state(|()| 7usize))
164 })
165 .to_with_state(filtered),
166 )
167 .route("/route", web::to_with_state(index))
168 .build(),
169 )
170 .await;
171
172 let check = async |method: Method, uri: &str, status: StatusCode, body: &str| {
173 let req = TestRequest::with_uri(uri).method(method).to_request();
174 let resp = srv.call(req).await.unwrap();
175 assert_eq!(resp.status(), status, "{uri}");
176 assert_eq!(read_body(resp).await, body.as_bytes(), "{uri}");
177 };
178
179 check(Method::GET, "/index", StatusCode::OK, "index:app").await;
180 check(Method::GET, "/item/10", StatusCode::OK, "item:app:10").await;
181 check(
182 Method::GET,
183 "/item/abc",
184 StatusCode::NOT_FOUND,
185 "Path deserialize error: can not parse \"abc\" to a u32",
186 )
187 .await;
188 check(Method::GET, "/multi", StatusCode::OK, "get").await;
189 check(Method::DELETE, "/multi", StatusCode::OK, "index:app").await;
190 check(Method::POST, "/multi", StatusCode::OK, "any").await;
191 check(Method::GET, "/fallback", StatusCode::OK, "get").await;
192 check(
193 Method::POST,
194 "/fallback",
195 StatusCode::OK,
196 "fallback:app:POST",
197 )
198 .await;
199 check(Method::GET, "/filtered", StatusCode::OK, "filtered:7").await;
200 check(Method::PUT, "/route", StatusCode::OK, "index:app").await;
201 assert_eq!(st.hits.get(), 3);
202 }
203
204 #[crate::rt_test]
210 async fn build_with() {
211 let st = AppState::new(Counter {
212 name: "fixed",
213 ..Counter::default()
214 });
215 let srv = App::<St>::new()
216 .route("/", web::get().to_with_state(index))
217 .build_with::<usize>(st.clone())
218 .pipeline(1usize)
219 .await
220 .unwrap();
221
222 let resp = srv.call(TestRequest::default().to_request()).await.unwrap();
223 assert_eq!(resp.status(), StatusCode::OK);
224 let resp = srv
225 .call(TestRequest::with_uri("/missing").to_request())
226 .await
227 .unwrap();
228 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
229 assert_eq!(st.hits.get(), 1);
230 }
231}