From 081b7582f26644b663d0e06cd2c3d95b0b7aaee6 Mon Sep 17 00:00:00 2001 From: Adrian Kappel Date: Fri, 21 Feb 2020 14:59:05 -0500 Subject: [PATCH] Add example for autoreloading server development (#449) --- Cargo.toml | 1 + examples/README.md | 4 ++++ examples/autoreload.rs | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 examples/autoreload.rs diff --git a/Cargo.toml b/Cargo.toml index dbf6f0a59..13d2c4807 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ pretty_env_logger = "0.3" serde_derive = "1.0" handlebars = "3.0.0" tokio = { version = "0.2", features = ["macros"] } +listenfd = "0.3" [features] default = ["multipart", "websocket"] diff --git a/examples/README.md b/examples/README.md index 21587b769..3f5ecb95e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -35,3 +35,7 @@ Hooray! `warp` also includes built-in support for WebSockets ### TLS - [`tls.rs`](./tls.rs) - can i haz security? + +### Autoreloading + +- [`autoreload.rs`](./autoreload.rs) - Change some code and watch the server reload automatically! diff --git a/examples/autoreload.rs b/examples/autoreload.rs new file mode 100644 index 000000000..4aabfdb6a --- /dev/null +++ b/examples/autoreload.rs @@ -0,0 +1,38 @@ +#![deny(warnings)] +use hyper::server::Server; +use listenfd::ListenFd; +use std::convert::Infallible; +use warp::Filter; + +extern crate listenfd; +/// You'll need to install `systemfd` and `cargo-watch`: +/// ``` +/// cargo install systemfd cargo-watch +/// ``` +/// And run with: +/// ``` +/// systemfd --no-pid -s http::3030 -- cargo watch -x 'run --example autoreload' +/// ``` +#[tokio::main] +async fn main() { + // Match any request and return hello world! + let routes = warp::any().map(|| "Hello, World!"); + + // hyper let's us build a server from a TcpListener (which will be + // useful shortly). Thus, we'll need to convert our `warp::Filter` into + // a `hyper::service::MakeService` for use with a `hyper::server::Server`. + let svc = warp::service(routes); + let make_svc = hyper::service::make_service_fn(|_: _| async move { Ok::<_, Infallible>(svc) }); + + let mut listenfd = ListenFd::from_env(); + // if listenfd doesn't take a TcpListener (i.e. we're not running via + // the command above), we fall back to explicitly binding to a given + // host:port. + let server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() { + Server::from_tcp(l).unwrap() + } else { + Server::bind(&([127, 0, 0, 1], 3030).into()) + }; + + server.serve(make_svc).await.unwrap(); +}