dioxus_server/serverfn.rs
1use crate::FullstackState;
2use axum::{
3 body::Body,
4 extract::{Request, State},
5 response::Response,
6 routing::MethodRouter,
7};
8use dioxus_fullstack_core::FullstackContext;
9use http::{Method, StatusCode};
10use std::{pin::Pin, prelude::rust_2024::Future};
11
12/// A function endpoint that can be called from the client.
13#[derive(Clone)]
14pub struct ServerFunction {
15 path: &'static str,
16 method: Method,
17 handler: fn() -> MethodRouter<FullstackState>,
18}
19
20impl ServerFunction {
21 /// Create a new server function object from a MethodRouter
22 pub const fn new(
23 method: Method,
24 path: &'static str,
25 handler: fn() -> MethodRouter<FullstackState>,
26 ) -> Self {
27 Self {
28 path,
29 method,
30 handler,
31 }
32 }
33
34 /// The path of the server function.
35 pub fn path(&self) -> &'static str {
36 self.path
37 }
38
39 /// The HTTP method the server function expects.
40 pub fn method(&self) -> Method {
41 self.method.clone()
42 }
43
44 /// Collect all globally registered server functions
45 pub fn collect() -> Vec<&'static ServerFunction> {
46 inventory::iter::<ServerFunction>().collect()
47 }
48
49 /// Create a `MethodRouter` for this server function that can be mounted on an `axum::Router`.
50 ///
51 /// This runs the handler inside the required `FullstackContext` scope and populates
52 /// `FullstackContext` so that the handler can use those features.
53 ///
54 /// It also runs the server function inside a tokio `LocalPool` to allow !Send futures.
55 pub fn method_router(&self) -> MethodRouter<FullstackState> {
56 (self.handler)()
57 }
58
59 /// Creates a new `MethodRouter` for the given method and !Send handler.
60 ///
61 /// This is used internally by the `ServerFunction` to create the method router that this
62 /// server function uses.
63 #[allow(clippy::type_complexity)]
64 pub fn make_handler(
65 method: Method,
66 handler: fn(State<FullstackContext>, Request) -> Pin<Box<dyn Future<Output = Response>>>,
67 ) -> MethodRouter<FullstackState> {
68 axum::routing::method_routing::on(
69 method
70 .try_into()
71 .expect("MethodFilter only supports standard HTTP methods"),
72 move |state: State<FullstackState>, request: Request| async move {
73 use tracing::Instrument;
74 let current_span = tracing::Span::current();
75 // Allow !Send futures by running in the render handlers pinned local pool
76 let result = state.rt.spawn_pinned(move || async move {
77 use dioxus_fullstack_core::FullstackContext;
78 use http::header::{ACCEPT, LOCATION, REFERER};
79 use http::StatusCode;
80
81 // todo: we're copying the parts here, but it'd be ideal if we didn't.
82 // We can probably just pass the URI in so the matching logic can work and then
83 // in the server function, do all extraction via FullstackContext. This ensures
84 // calls to `.remove()` work as expected.
85 let (parts, body) = request.into_parts();
86 let server_context = FullstackContext::new(parts.clone());
87 let request = axum::extract::Request::from_parts(parts, body);
88
89 // store Accepts and Referrer in case we need them for redirect (below)
90 let referrer = request.headers().get(REFERER).cloned();
91 let accepts_html = request
92 .headers()
93 .get(ACCEPT)
94 .and_then(|v| v.to_str().ok())
95 .map(|v| v.contains("text/html"))
96 .unwrap_or(false);
97
98 server_context
99 .clone()
100 .scope(async move {
101 // Run the next middleware / handler inside the server context
102 let mut response = handler(State(server_context), request)
103 .instrument(current_span)
104 .await;
105
106 let server_context = FullstackContext::current().expect(
107 "Server context should be available inside the server context scope",
108 );
109
110 // Get the extra response headers set during the handler and add them to the response
111 let headers = server_context.take_response_headers();
112 if let Some(headers) = headers {
113 response.headers_mut().extend(headers);
114 }
115
116 // If the response is successful and accepts text/html (i.e., is a
117 // plain form post) and doesn't already have a Location set, then
118 // redirect to Referer. Only redirect on success so that error
119 // responses (4xx, 5xx) propagate correctly to the client.
120 if accepts_html && response.status().is_success()
121 && let Some(referrer) = referrer {
122 let has_location = response.headers().get(LOCATION).is_some();
123 if !has_location {
124 *response.status_mut() = StatusCode::FOUND;
125 response.headers_mut().insert(LOCATION, referrer);
126 }
127 }
128
129 response
130 })
131 .await
132 }).await;
133
134 match result {
135 Ok(response) => response,
136 Err(err) => Response::builder()
137 .status(StatusCode::INTERNAL_SERVER_ERROR)
138 .body(Body::new(if cfg!(debug_assertions) {
139 format!("Server function panicked: {}", err)
140 } else {
141 "Internal Server Error".to_string()
142 }))
143 .unwrap(),
144 }
145 },
146 )
147 }
148}
149
150impl inventory::Collect for ServerFunction {
151 #[inline]
152 fn registry() -> &'static inventory::Registry {
153 static REGISTRY: inventory::Registry = inventory::Registry::new();
154 ®ISTRY
155 }
156}