salvo.rs 1.7 KB

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