From 592dc5f7f9e8863258b2739101871f6bfc8b4131 Mon Sep 17 00:00:00 2001 From: Marek Kuskowski <50183564+nylonicious@users.noreply.github.com> Date: Sat, 23 Jul 2022 18:27:36 +0200 Subject: [PATCH] Add ws example showing how to pass data to callback (#1185) --- axum/src/extract/ws.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/axum/src/extract/ws.rs b/axum/src/extract/ws.rs index 5d8f6005e9..5643c819b1 100644 --- a/axum/src/extract/ws.rs +++ b/axum/src/extract/ws.rs @@ -36,6 +36,37 @@ //! # }; //! ``` //! +//! # Passing data and/or state to an `on_upgrade` callback +//! +//! ``` +//! use axum::{ +//! extract::ws::{WebSocketUpgrade, WebSocket}, +//! response::Response, +//! routing::get, +//! Extension, Router, +//! }; +//! +//! #[derive(Clone)] +//! struct State { +//! // ... +//! } +//! +//! async fn handler(ws: WebSocketUpgrade, Extension(state): Extension) -> Response { +//! ws.on_upgrade(|socket| handle_socket(socket, state)) +//! } +//! +//! async fn handle_socket(socket: WebSocket, state: State) { +//! // ... +//! } +//! +//! let app = Router::new() +//! .route("/ws", get(handler)) +//! .layer(Extension(State { /* ... */ })); +//! # async { +//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); +//! # }; +//! ``` +//! //! # Read and write concurrently //! //! If you need to read and write concurrently from a [`WebSocket`] you can use