warp.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use dioxus::prelude::*;
  2. use dioxus_liveview::LiveView;
  3. use std::net::SocketAddr;
  4. use warp::ws::Ws;
  5. use warp::Filter;
  6. fn app(cx: Scope) -> Element {
  7. let mut num = use_state(cx, || 0);
  8. cx.render(rsx! {
  9. div {
  10. "hello world! {num}"
  11. button {
  12. onclick: move |_| num += 1,
  13. "Increment"
  14. }
  15. }
  16. })
  17. }
  18. #[tokio::main]
  19. async fn main() {
  20. pretty_env_logger::init();
  21. let addr: SocketAddr = ([127, 0, 0, 1], 3030).into();
  22. let index = warp::path::end().map(move || {
  23. warp::reply::html(format!(
  24. r#"
  25. <!DOCTYPE html>
  26. <html>
  27. <head> <title>Dioxus LiveView with Warp</title> </head>
  28. <body> <div id="main"></div> </body>
  29. {glue}
  30. </html>
  31. "#,
  32. glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws/"))
  33. ))
  34. });
  35. let view = LiveView::new();
  36. let ws = warp::path("ws")
  37. .and(warp::ws())
  38. .and(warp::any().map(move || view.clone()))
  39. .map(move |ws: Ws, view: LiveView| {
  40. println!("Got a connection!");
  41. ws.on_upgrade(|ws| async move {
  42. let _ = view.upgrade_warp(ws, app).await;
  43. })
  44. });
  45. println!("Listening on http://{}", addr);
  46. warp::serve(index.or(ws)).run(addr).await;
  47. }