axum.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use axum::{extract::ws::WebSocketUpgrade, response::Html, routing::get, Router};
  2. use dioxus::prelude::*;
  3. fn app(cx: Scope) -> Element {
  4. let mut num = use_state(cx, || 0);
  5. cx.render(rsx! {
  6. div {
  7. "hello axum! {num}"
  8. button { onclick: move |_| num += 1, "Increment" }
  9. }
  10. })
  11. }
  12. #[tokio::main]
  13. async fn main() {
  14. pretty_env_logger::init();
  15. let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
  16. let view = dioxus_liveview::LiveViewPool::new();
  17. let index_page_with_glue = |glue: &str| {
  18. Html(format!(
  19. r#"
  20. <!DOCTYPE html>
  21. <html>
  22. <head> <title>Dioxus LiveView with axum</title> </head>
  23. <body> <div id="main"></div> </body>
  24. {glue}
  25. </html>
  26. "#,
  27. ))
  28. };
  29. let app =
  30. Router::new()
  31. .route(
  32. "/",
  33. get(move || async move {
  34. index_page_with_glue(&dioxus_liveview::interpreter_glue(&format!(
  35. "ws://{addr}/ws"
  36. )))
  37. }),
  38. )
  39. .route(
  40. "/as-path",
  41. get(move || async move {
  42. index_page_with_glue(&dioxus_liveview::interpreter_glue("/ws"))
  43. }),
  44. )
  45. .route(
  46. "/ws",
  47. get(move |ws: WebSocketUpgrade| async move {
  48. ws.on_upgrade(move |socket| async move {
  49. _ = view.launch(dioxus_liveview::axum_socket(socket), app).await;
  50. })
  51. }),
  52. );
  53. println!("Listening on http://{addr}");
  54. axum::Server::bind(&addr.to_string().parse().unwrap())
  55. .serve(app.into_make_service())
  56. .await
  57. .unwrap();
  58. }