server_context.rs 4.2 KB

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