axum.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 app = Router::new()
  18. .route(
  19. "/",
  20. get(move || async move {
  21. Html(format!(
  22. r#"
  23. <!DOCTYPE html>
  24. <html>
  25. <head> <title>Dioxus LiveView with Warp</title> </head>
  26. <body> <div id="main"></div> </body>
  27. {glue}
  28. </html>
  29. "#,
  30. glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws"))
  31. ))
  32. }),
  33. )
  34. .route(
  35. "/ws",
  36. get(move |ws: WebSocketUpgrade| async move {
  37. ws.on_upgrade(move |socket| async move {
  38. _ = view.launch(dioxus_liveview::axum_socket(socket), app).await;
  39. })
  40. }),
  41. );
  42. println!("Listening on http://{addr}");
  43. axum::Server::bind(&addr.to_string().parse().unwrap())
  44. .serve(app.into_make_service())
  45. .await
  46. .unwrap();
  47. }