Skip to content

Commit 58f63bb

Browse files
authored
Add WebSocketUpgrade::selected_protocol (#3248)
1 parent 6bf1fcb commit 58f63bb

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

axum/src/extract/ws.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,15 @@ impl<F> WebSocketUpgrade<F> {
265265
self
266266
}
267267

268+
/// Return the selected WebSocket subprotocol, if one has been chosen.
269+
///
270+
/// If [`protocols()`][Self::protocols] has been called and a matching
271+
/// protocol has been selected, the return value will be `Some` containing
272+
/// said protocol. Otherwise, it will be `None`.
273+
pub fn selected_protocol(&self) -> Option<&HeaderValue> {
274+
self.protocol.as_ref()
275+
}
276+
268277
/// Provide a callback to call if upgrading the connection fails.
269278
///
270279
/// The connection upgrade is performed in a background task. If that fails this callback
@@ -1154,6 +1163,7 @@ mod tests {
11541163

11551164
fn echo_app() -> Router {
11561165
async fn handle_socket(mut socket: WebSocket) {
1166+
assert_eq!(socket.protocol().unwrap(), "echo");
11571167
while let Some(Ok(msg)) = socket.recv().await {
11581168
match msg {
11591169
Message::Text(_) | Message::Binary(_) | Message::Close(_) => {
@@ -1171,7 +1181,9 @@ mod tests {
11711181
Router::new().route(
11721182
"/echo",
11731183
any(|ws: WebSocketUpgrade| {
1174-
ready(ws.protocols(["echo2", "echo"]).on_upgrade(handle_socket))
1184+
let ws = ws.protocols(["echo2", "echo"]);
1185+
assert_eq!(ws.selected_protocol().unwrap(), "echo");
1186+
ready(ws.on_upgrade(handle_socket))
11751187
}),
11761188
)
11771189
}

0 commit comments

Comments
 (0)