diff --git a/Cargo.toml b/Cargo.toml index 5d64cfd91..3ca8aea83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,9 @@ required-features = ["compress"] name = "test_server" required-features = ["compress"] +[[example]] +name = "on_connect" + [dependencies] actix-codec = "0.3.0" actix-service = "1.0.6" diff --git a/examples/on_connect.rs b/examples/on_connect.rs new file mode 100644 index 000000000..0772515da --- /dev/null +++ b/examples/on_connect.rs @@ -0,0 +1,31 @@ +//! This example shows how to use `actix_web::HttpServer::on_connect` + +#[derive(Clone)] +struct ConnectionInfo(String); + +async fn route_whoami(req: actix_web::HttpRequest) -> String { + let extensions = req.extensions(); + let conn_info = extensions.get::().unwrap(); + format!("Here is some info about you: {}", conn_info.0) +} + +fn on_connect(connection: &dyn std::any::Any) -> ConnectionInfo { + let sock = connection.downcast_ref::().unwrap(); + let msg = format!("local_addr={:?}\npeer_addr={:?}", sock.local_addr(),sock.peer_addr()); + ConnectionInfo(msg) +} + +#[actix_rt::main] +async fn main() -> std::io::Result<()> { + std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info"); + env_logger::init(); + + actix_web::HttpServer::new(|| { + actix_web::App::new().route("/", actix_web::web::get().to(route_whoami)) + }) + .on_connect(std::sync::Arc::new(on_connect)) + .bind("127.0.0.1:8080")? + .workers(1) + .run() + .await +} diff --git a/src/server.rs b/src/server.rs index ac850f5c5..3f659803a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -102,6 +102,7 @@ where /// - `actix_tls::openssl::SslStream` when using openssl. /// - `actix_tls::rustls::TlsStream` when using rustls. /// - `tokio::net::TcpStream` when no encryption is used. + /// See `on_connect` example for additional details. pub fn on_connect( self, f: Arc C + Send + Sync>,