webserver_base/webserver/
not_found.rs1use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use axum::http::Uri;
13use serde::Serialize;
14use serde_json::Value;
15use tracing::error;
16
17use super::state::WebServerState;
18
19type Hook<S> =
20 dyn Fn(WebServerState<S>, Uri) -> Pin<Box<dyn Future<Output = Value> + Send>> + Send + Sync;
21
22pub struct NotFound<S = ()> {
28 hook: Option<Arc<Hook<S>>>,
29}
30
31impl<S> NotFound<S>
32where
33 S: Clone + Send + Sync + 'static,
34{
35 #[must_use]
37 pub const fn none() -> Self {
38 Self { hook: None }
39 }
40
41 #[must_use]
47 pub fn with<F, Fut, A>(hook: F) -> Self
48 where
49 F: Fn(WebServerState<S>, Uri) -> Fut + Send + Sync + 'static,
50 Fut: Future<Output = A> + Send + 'static,
51 A: Serialize,
52 {
53 Self {
54 hook: Some(Arc::new(move |state: WebServerState<S>, uri: Uri| {
55 let data: Fut = hook(state, uri);
56 Box::pin(async move { to_value_or_null(&data.await) })
57 })),
58 }
59 }
60
61 pub(super) async fn data(&self, state: WebServerState<S>, uri: Uri) -> Value {
63 match &self.hook {
64 None => Value::Null,
65 Some(hook) => hook(state, uri).await,
66 }
67 }
68}
69
70impl<S> Clone for NotFound<S> {
71 fn clone(&self) -> Self {
72 Self {
73 hook: self.hook.clone(),
74 }
75 }
76}
77
78impl<S> Default for NotFound<S>
79where
80 S: Clone + Send + Sync + 'static,
81{
82 fn default() -> Self {
83 Self::none()
84 }
85}
86
87fn to_value_or_null<A>(data: &A) -> Value
88where
89 A: Serialize,
90{
91 serde_json::to_value(data).unwrap_or_else(|serialize_error| {
92 error!("the 404 hook's data is unserializable, rendering with null: {serialize_error}");
93 Value::Null
94 })
95}