Add example

This commit is contained in:
Mikail Bagishov 2020-05-02 00:20:08 +03:00 committed by Rob Ede
parent da22edef36
commit b56a5295d3
No known key found for this signature in database
GPG Key ID: C2A3B36E841A91E6
3 changed files with 35 additions and 0 deletions

View File

@ -64,6 +64,9 @@ required-features = ["compress"]
name = "test_server" name = "test_server"
required-features = ["compress"] required-features = ["compress"]
[[example]]
name = "on_connect"
[dependencies] [dependencies]
actix-codec = "0.3.0" actix-codec = "0.3.0"
actix-service = "1.0.6" actix-service = "1.0.6"

31
examples/on_connect.rs Normal file
View File

@ -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::<ConnectionInfo>().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::<actix_rt::net::TcpStream>().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
}

View File

@ -102,6 +102,7 @@ where
/// - `actix_tls::openssl::SslStream<tokio::net::TcpStream>` when using openssl. /// - `actix_tls::openssl::SslStream<tokio::net::TcpStream>` when using openssl.
/// - `actix_tls::rustls::TlsStream<tokio::net::TcpStream>` when using rustls. /// - `actix_tls::rustls::TlsStream<tokio::net::TcpStream>` when using rustls.
/// - `tokio::net::TcpStream` when no encryption is used. /// - `tokio::net::TcpStream` when no encryption is used.
/// See `on_connect` example for additional details.
pub fn on_connect<C>( pub fn on_connect<C>(
self, self,
f: Arc<dyn Fn(&dyn std::any::Any) -> C + Send + Sync>, f: Arc<dyn Fn(&dyn std::any::Any) -> C + Send + Sync>,