hello_world_liveview.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // ANCHOR: all
  2. use axum::{extract::ws::WebSocketUpgrade, response::Html, routing::get, Router};
  3. use dioxus::prelude::*;
  4. // ANCHOR: glue
  5. #[tokio::main]
  6. async fn main() {
  7. let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
  8. let view = dioxus_liveview::LiveViewPool::new();
  9. let app = Router::new()
  10. // The root route contains the glue code to connect to the WebSocket
  11. .route(
  12. "/",
  13. get(move || async move {
  14. Html(format!(
  15. r#"
  16. <!DOCTYPE html>
  17. <html>
  18. <head> <title>Dioxus LiveView with Axum</title> </head>
  19. <body> <div id="main"></div> </body>
  20. {glue}
  21. </html>
  22. "#,
  23. // Create the glue code to connect to the WebSocket on the "/ws" route
  24. glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws"))
  25. ))
  26. }),
  27. )
  28. // The WebSocket route is what Dioxus uses to communicate with the browser
  29. .route(
  30. "/ws",
  31. get(move |ws: WebSocketUpgrade| async move {
  32. ws.on_upgrade(move |socket| async move {
  33. // When the WebSocket is upgraded, launch the LiveView with the app component
  34. _ = view.launch(dioxus_liveview::axum_socket(socket), app).await;
  35. })
  36. }),
  37. );
  38. println!("Listening on http://{addr}");
  39. axum::Server::bind(&addr.to_string().parse().unwrap())
  40. .serve(app.into_make_service())
  41. .await
  42. .unwrap();
  43. }
  44. // ANCHOR_END: glue
  45. // ANCHOR: app
  46. fn app(cx: Scope) -> Element {
  47. cx.render(rsx! {
  48. div {
  49. "Hello, world!"
  50. }
  51. })
  52. }
  53. // ANCHOR_END: app
  54. // ANCHOR_END: all