Add protocol field to WebSocket (#1022)

* Add protocol field to WebSocket

Signed-off-by: Matteo Joliveau <matteojoliveau@gmail.com>

* Use HeaderValue instead of String

Signed-off-by: Matteo Joliveau <matteojoliveau@gmail.com>

* Update axum/src/extract/ws.rs

Co-authored-by: Jonas Platte <jplatte+git@posteo.de>

* Update changelog

Co-authored-by: David Pedersen <david.pdrsn@gmail.com>
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
This commit is contained in:
Matteo Joliveau 2022-05-11 10:49:44 +02:00 committed by GitHub
parent cfdac03c8d
commit 280334347b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 2 deletions

View file

@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased
- None.
- **added:** Add `WebSocket::protocol` to return the selected WebSocket subprotocol, if there is one. ([#1022])
[#1022]: https://github.com/tokio-rs/axum/pull/1022
# 0.5.5 (10. May, 2022)

View file

@ -207,12 +207,17 @@ impl WebSocketUpgrade {
let on_upgrade = self.on_upgrade;
let config = self.config;
let protocol = self.protocol.clone();
tokio::spawn(async move {
let upgraded = on_upgrade.await.expect("connection upgrade failed");
let socket =
WebSocketStream::from_raw_socket(upgraded, protocol::Role::Server, Some(config))
.await;
let socket = WebSocket { inner: socket };
let socket = WebSocket {
inner: socket,
protocol,
};
callback(socket).await;
});
@ -309,6 +314,7 @@ fn header_contains<B>(req: &RequestParts<B>, key: HeaderName, value: &'static st
#[derive(Debug)]
pub struct WebSocket {
inner: WebSocketStream<Upgraded>,
protocol: Option<HeaderValue>,
}
impl WebSocket {
@ -331,6 +337,11 @@ impl WebSocket {
pub async fn close(mut self) -> Result<(), Error> {
self.inner.close(None).await.map_err(Error::new)
}
/// Return the selected WebSocket subprotocol, if one has been chosen.
pub fn protocol(&self) -> Option<&HeaderValue> {
self.protocol.as_ref()
}
}
impl Stream for WebSocket {