salvo.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #[cfg(not(feature = "salvo"))]
  2. fn main() {}
  3. #[cfg(feature = "salvo")]
  4. #[tokio::main]
  5. async fn main() {
  6. use std::sync::Arc;
  7. use dioxus_core::{Element, LazyNodes, Scope};
  8. use dioxus_liveview as liveview;
  9. use dioxus_liveview::Liveview;
  10. use salvo::extra::affix;
  11. use salvo::extra::ws::WsHandler;
  12. use salvo::prelude::*;
  13. fn app(cx: Scope) -> Element {
  14. cx.render(LazyNodes::new(|f| f.text(format_args!("hello world!"))))
  15. }
  16. pretty_env_logger::init();
  17. let addr = ([127, 0, 0, 1], 3030);
  18. // todo: compactify this routing under one liveview::app method
  19. let view = liveview::new(addr);
  20. let router = Router::new()
  21. .hoop(affix::inject(Arc::new(view)))
  22. .get(index)
  23. .push(Router::with_path("app").get(connect));
  24. Server::new(TcpListener::bind(addr)).serve(router).await;
  25. #[handler]
  26. fn index(depot: &mut Depot, res: &mut Response) {
  27. let view = depot.obtain::<Arc<Liveview>>().unwrap();
  28. let body = view.body("<title>Dioxus LiveView</title>");
  29. res.render(Text::Html(body));
  30. }
  31. #[handler]
  32. async fn connect(
  33. req: &mut Request,
  34. depot: &mut Depot,
  35. res: &mut Response,
  36. ) -> Result<(), StatusError> {
  37. let view = depot.obtain::<Arc<Liveview>>().unwrap().clone();
  38. let fut = WsHandler::new().handle(req, res)?;
  39. let fut = async move {
  40. if let Some(ws) = fut.await {
  41. view.upgrade_salvo(ws, app).await;
  42. }
  43. };
  44. tokio::task::spawn(fut);
  45. Ok(())
  46. }
  47. }