1
0

server_context_state.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #![allow(non_snake_case, unused)]
  2. use dioxus::prelude::*;
  3. use dioxus_fullstack::prelude::*;
  4. #[cfg(feature = "ssr")]
  5. #[derive(Default, Clone)]
  6. struct ServerFunctionState {
  7. call_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
  8. }
  9. fn main() {
  10. #[cfg(feature = "web")]
  11. dioxus_web::launch_with_props(
  12. app,
  13. // Get the root props from the document
  14. get_root_props_from_document().unwrap_or_default(),
  15. dioxus_web::Config::new().hydrate(true),
  16. );
  17. #[cfg(feature = "ssr")]
  18. {
  19. use axum::body::Body;
  20. use axum::extract::Path;
  21. use axum::extract::State;
  22. use axum::http::Request;
  23. use axum::routing::get;
  24. use std::sync::Arc;
  25. tokio::runtime::Runtime::new()
  26. .unwrap()
  27. .block_on(async move {
  28. let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  29. axum::Server::bind(&addr)
  30. .serve(
  31. axum::Router::new()
  32. // Serve the dist folder with the static javascript and WASM files created by the dixous CLI
  33. .serve_static_assets("./dist")
  34. // Register server functions
  35. .register_server_fns_with_handler("", |func| {
  36. move |State(server_fn_state): State<ServerFunctionState>, req: Request<Body>| async move {
  37. let (parts, body) = req.into_parts();
  38. let parts: Arc<RequestParts> = Arc::new(parts.into());
  39. let mut server_context = DioxusServerContext::new(parts.clone());
  40. server_context.insert(server_fn_state);
  41. server_fn_handler(server_context, func.clone(), parts, body).await
  42. }
  43. })
  44. .with_state(ServerFunctionState::default())
  45. // Connect to the hot reload server in debug mode
  46. .connect_hot_reload()
  47. // Render the application. This will serialize the root props (the intial count) into the HTML
  48. .route(
  49. "/",
  50. get(move |State(ssr_state): State<SSRState>| async move { axum::body::Full::from(
  51. ssr_state.render(
  52. &ServeConfigBuilder::new(
  53. app,
  54. 0,
  55. )
  56. .build(),
  57. )
  58. )}),
  59. )
  60. // Render the application with a different intial count
  61. .route(
  62. "/:initial_count",
  63. get(move |Path(intial_count): Path<usize>, State(ssr_state): State<SSRState>| async move { axum::body::Full::from(
  64. ssr_state.render(
  65. &ServeConfigBuilder::new(
  66. app,
  67. intial_count,
  68. )
  69. .build(),
  70. )
  71. )}),
  72. )
  73. .with_state(SSRState::default())
  74. .into_make_service(),
  75. )
  76. .await
  77. .unwrap();
  78. });
  79. }
  80. }
  81. fn app(cx: Scope<usize>) -> Element {
  82. let mut count = use_state(cx, || *cx.props);
  83. cx.render(rsx! {
  84. h1 { "High-Five counter: {count}" }
  85. button { onclick: move |_| count += 1, "Up high!" }
  86. button { onclick: move |_| count -= 1, "Down low!" }
  87. button {
  88. onclick: move |_| {
  89. to_owned![count];
  90. async move {
  91. // Call the server function just like a local async function
  92. if let Ok(new_count) = double_server(*count.current()).await {
  93. count.set(new_count);
  94. }
  95. }
  96. },
  97. "Double"
  98. }
  99. })
  100. }
  101. // We use the "getcbor" encoding to make caching easier
  102. #[server(DoubleServer, "", "getcbor")]
  103. async fn double_server(number: usize) -> Result<usize, ServerFnError> {
  104. // Perform some expensive computation or access a database on the server
  105. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  106. let result = number * 2;
  107. let cx = server_context();
  108. println!(
  109. "User Agent {:?}",
  110. cx.request_parts().headers.get("User-Agent")
  111. );
  112. // Set the cache control header to 1 hour on the post request
  113. cx.response_headers_mut()
  114. .insert("Cache-Control", "max-age=3600".parse().unwrap());
  115. // Get the server function state
  116. let server_fn_state = cx.get::<ServerFunctionState>().unwrap();
  117. let call_count = server_fn_state
  118. .call_count
  119. .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
  120. println!("server functions have been called {call_count} times");
  121. println!("server calculated {result}");
  122. Ok(result)
  123. }