我希望这不是太模糊。
我正在与Tauri玩,在那里我想公开一个基于网络的控制面板的应用。通过访问本地网络上的url (如http://192.168.1.101:8000/some-action ),它将向运行在该机器上的Tauri应用程序发送窗口消息。想象一下,在办公室里有一个仪表板应用程序,网络上的用户可以通过一个web url来控制应用程序的行为。
到目前为止,这是我的生锈代码:
// use rocket runtime
#[rocket::main]
async fn main() {
tauri::Builder::default()
.setup(|app| {
let window = app.get_window("main").unwrap();
#[get("/")]
fn index() {
// this is where I want to emit the window event if possible
//window.emit("from-rust", format!("message")).expect("failed to emit");
}
// mount the rocket instance
tauri::async_runtime::spawn(async move {
let _rocket = rocket::build()
.mount("/", routes![index])
.launch().await;
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}我能够运行火箭服务器,但是,我无法解决如何从火箭请求处理函数发送窗口事件。
如有任何建议或见解,将不胜感激。
发布于 2022-11-30 12:10:29
不允许fn项捕获它们的环境。但是,由于#[get(...)]只允许在fn上使用,所以不能使用它。
不过,您可以自己实现自定义结构所需的特征。
use async_trait::async_trait;
use rocket::http::Method;
use rocket::route::{Handler, Outcome};
use rocket::{Data, Request, Route};
use tauri::{Manager, generate_context};
#[derive(Clone)]
struct WindowHandler {
window: tauri::Window,
}
impl WindowHandler {
fn new(window: tauri::Window) -> Self {
Self { window }
}
}
#[async_trait]
impl Handler for WindowHandler {
async fn handle<'r>(&self, request: &'r Request<'_>, data: Data<'r>) -> Outcome<'r> {
self.window
.emit("from-rust", format!("message"))
.expect("failed to emit");
todo!()
}
}
impl From<WindowHandler> for Vec<Route> {
fn from(value: WindowHandler) -> Self {
vec![Route::new(Method::Get, "/", value)]
}
}
#[rocket::main]
async fn main() {
tauri::Builder::default()
.setup(|app| {
let window = app.get_window("main").unwrap();
let index = WindowHandler::new(window);
// mount the rocket instance
tauri::async_runtime::spawn(async move {
let _rocket = rocket::build().mount("/", index).launch().await;
});
Ok(())
})
.run(generate_context!())
.expect("error while running tauri application");
}或者另一种可能是使用这样的全局WINDOW: OnceLock<Window>:
#![feature(once_cell)]
use std::sync::OnceLock;
use rocket::{get, routes};
use tauri::{Manager, generate_context, Window};
static WINDOW: OnceLock<Window> = OnceLock::new();
#[rocket::main]
async fn main() {
tauri::Builder::default()
.setup(|app| {
let window = app.get_window("main").unwrap();
_ = WINDOW.set(window);
#[get("/")]
fn index() {
WINDOW.get().expect("window is available").emit("from-rust", format!("message")).expect("failed to emit");
}
// mount the rocket instance
tauri::async_runtime::spawn(async move {
let _rocket = rocket::build().mount("/", routes![index]).launch().await;
});
Ok(())
})
.run(generate_context!())
.expect("error while running tauri application");
}https://stackoverflow.com/questions/74626272
复制相似问题