diff --git a/Cargo.toml b/Cargo.toml index a08198ba3..5495c6a39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -116,5 +116,6 @@ members = [ "examples/websocket-chat", "examples/web-cors/backend", "examples/unix-socket", + "examples/catflap", "tools/wsload/", ] diff --git a/examples/catflap/Cargo.toml b/examples/catflap/Cargo.toml new file mode 100644 index 000000000..0cde544ad --- /dev/null +++ b/examples/catflap/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "catflap" +version = "0.1.0" +authors = ["ivegotasthma "] +workspace = "../.." + +[dependencies] +env_logger = "0.5" +actix = "0.5" +actix-web = { path = "../../" } diff --git a/examples/catflap/README.md b/examples/catflap/README.md new file mode 100644 index 000000000..166332fa7 --- /dev/null +++ b/examples/catflap/README.md @@ -0,0 +1,24 @@ +# catflap + +There is the utility [cargo-watch](https://github.com/passcod/cargo-watch) which rebuilds your project when it notices +there are changed files. This is very useful when writing web server and you want to have a fast edit, compile, run +cycle. + +The problem is that when you're using this for a web server the socket that the server uses might still be in use +from the previous run. This makes `cargo-watch` crash. The solution, from the author of `cargo-watch` is `catflap`. It's +another utility that takes ownership of sockets and passes them the program you're running with cargo watch. + +To be able to use the sockets provided by `catflap` you need to read the file descriptor from the environment variable +`LISTEN_FD`. + +This example will how you how to do that on a hello world. + +By default the server will be running on port `5000`, unless you pass the flag `-p 8080` to catflap. Then it will run on +port `8080` + +## Usage +```bash +cd actix-web/examples/catflap +catflap -- cargo watch -x run +# Started http server: 127.0.0.1:8080 +``` diff --git a/examples/catflap/src/main.rs b/examples/catflap/src/main.rs new file mode 100644 index 000000000..6f2238a53 --- /dev/null +++ b/examples/catflap/src/main.rs @@ -0,0 +1,29 @@ +extern crate actix; +extern crate actix_web; +extern crate env_logger; + +use actix_web::*; + + +fn index(_req: HttpRequest) -> &'static str { + "hello, world" +} + +fn main() { + ::std::env::set_var("RUST_LOG", "actix_web=info"); + let _ = env_logger::init(); + let sys = actix::System::new("catflap-example"); + + let fd = std::env::var("LISTEN_FD").ok() + .and_then(|fd| fd.parse().ok()) + .expect("couldn't get LISTEN_FD env variable"); + + let _addr = HttpServer::new( + || Application::new() + .resource("/", |r| r.f(index))) + .bind_socket(fd).unwrap() + .start(); + + println!("Started http server."); + let _ = sys.run(); +}