rocket.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #[macro_use]
  2. extern crate rocket;
  3. use dioxus::prelude::*;
  4. use dioxus_liveview::LiveViewPool;
  5. use rocket::response::content::RawHtml;
  6. use rocket::{Config, Rocket, State};
  7. use rocket_ws::{Channel, WebSocket};
  8. fn app(cx: Scope) -> Element {
  9. let mut num = use_state(cx, || 0);
  10. cx.render(rsx! {
  11. div {
  12. "hello Rocket! {num}"
  13. button { onclick: move |_| num += 1, "Increment" }
  14. }
  15. })
  16. }
  17. fn index_page_with_glue(glue: &str) -> RawHtml<String> {
  18. RawHtml(format!(
  19. r#"
  20. <!DOCTYPE html>
  21. <html>
  22. <head> <title>Dioxus LiveView with Rocket</title> </head>
  23. <body> <div id="main"></div> </body>
  24. {glue}
  25. </html>
  26. "#,
  27. glue = glue
  28. ))
  29. }
  30. #[get("/")]
  31. async fn index(config: &Config) -> RawHtml<String> {
  32. index_page_with_glue(&dioxus_liveview::interpreter_glue(&format!(
  33. "ws://{addr}:{port}/ws",
  34. addr = config.address,
  35. port = config.port,
  36. )))
  37. }
  38. #[get("/as-path")]
  39. async fn as_path() -> RawHtml<String> {
  40. index_page_with_glue(&dioxus_liveview::interpreter_glue("/ws"))
  41. }
  42. #[get("/ws")]
  43. fn ws(ws: WebSocket, pool: &State<LiveViewPool>) -> Channel<'static> {
  44. let pool = pool.inner().to_owned();
  45. ws.channel(move |stream| {
  46. Box::pin(async move {
  47. let _ = pool
  48. .launch(dioxus_liveview::rocket_socket(stream), app)
  49. .await;
  50. Ok(())
  51. })
  52. })
  53. }
  54. #[tokio::main]
  55. async fn main() {
  56. let view = dioxus_liveview::LiveViewPool::new();
  57. Rocket::build()
  58. .manage(view)
  59. .mount("/", routes![index, as_path, ws])
  60. .ignite()
  61. .await
  62. .expect("Failed to ignite rocket")
  63. .launch()
  64. .await
  65. .expect("Failed to launch rocket");
  66. }