1
0

salvo.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use dioxus::prelude::*;
  2. use dioxus_liveview::LiveViewPool;
  3. use salvo::affix;
  4. use salvo::prelude::*;
  5. use std::net::SocketAddr;
  6. use std::sync::Arc;
  7. fn app(cx: Scope) -> Element {
  8. let mut num = use_state(cx, || 0);
  9. cx.render(rsx! {
  10. div {
  11. "hello salvo! {num}"
  12. button { onclick: move |_| num += 1, "Increment" }
  13. }
  14. })
  15. }
  16. #[tokio::main]
  17. async fn main() {
  18. pretty_env_logger::init();
  19. let addr: SocketAddr = ([127, 0, 0, 1], 3030).into();
  20. let view = LiveViewPool::new();
  21. let router = Router::new()
  22. .hoop(affix::inject(Arc::new(view)))
  23. .get(index)
  24. .push(Router::with_path("ws").get(connect));
  25. println!("Listening on http://{}", addr);
  26. Server::new(TcpListener::bind(addr)).serve(router).await;
  27. }
  28. #[handler]
  29. fn index(_depot: &mut Depot, res: &mut Response) {
  30. let addr: SocketAddr = ([127, 0, 0, 1], 3030).into();
  31. res.render(Text::Html(format!(
  32. r#"
  33. <!DOCTYPE html>
  34. <html>
  35. <head> <title>Dioxus LiveView with Warp</title> </head>
  36. <body> <div id="main"></div> </body>
  37. {glue}
  38. </html>
  39. "#,
  40. glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws"))
  41. )));
  42. }
  43. #[handler]
  44. async fn connect(
  45. req: &mut Request,
  46. depot: &mut Depot,
  47. res: &mut Response,
  48. ) -> Result<(), StatusError> {
  49. let view = depot.obtain::<Arc<LiveViewPool>>().unwrap().clone();
  50. WebSocketUpgrade::new()
  51. .upgrade(req, res, |ws| async move {
  52. _ = view.launch(dioxus_liveview::salvo_socket(ws), app).await;
  53. })
  54. .await
  55. }