在开发过程中,让cargo在更改时自动重新编译代码会非常方便。这可以通过使用cargo-watch来完成。由于应用程序通常会绑定到端口以侦听传入的HTTP请求,因此将其与listenfd和systemfd 实用程序结合使用以确保套接字在应用程序编译和重新加载时保持打开状态是有意义的。
systemfd将打开一个套接字并将其传递给cargo-watch,以监视更改,然后调用编译器并运行您的应用。然后应用程序将listenfd用于拾取systemfd打开的套接字.
要获得自动重装,您需要安装cargo-watch和 安装systemfd。两者都是用Rust编写的,cargo install可以安装:
cargo install systemfd cargo-watch
您需要稍微修改一下应用程序,以便它可以拾取由systemfd打开的外部套接字。将listenfd依赖项添加到您的应用程序:
\[dependencies]
listenfd = "0.3"
然后修改服务器代码,使其仅作为bind后备调用:
use kayrx::web::{web, App, HttpRequest, HttpServer, Responder};
use listenfd::ListenFd;
async fn index(_req: HttpRequest) -> impl Responder {
"Hello World!"
}
#\[kayrx::main]
async fn main() -> std::io::Result<()> {
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(|| App::new().route("/", web::get().to(index)));
server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
server.listen(l)?
} else {
server.bind("127.0.0.1:3000")?
};
server.run().await
}
现在要运行开发服务器,请用以下命令:
systemfd --no-pid -s http::3000 -- cargo watch -x run
[set title Kayrx / autoreload]
[set doc-section pattern-autoreload]
[stash doc-content][require raw ../_side.html]