Struct WebSocketUpgrade

struct WebSocketUpgrade<F = DefaultOnFailedUpgrade> { ... }

Extractor for establishing WebSocket connections.

For HTTP/1.1 requests, this extractor requires the request method to be GET; in later versions, CONNECT is used instead. To support both, it should be used with any.

See the module docs for an example.

Implementations

impl<F> WebSocketUpgrade<F>

fn read_buffer_size(self: Self, size: usize) -> Self

Read buffer capacity. The default value is 128KiB

fn write_buffer_size(self: Self, size: usize) -> Self

The target minimum size of the write buffer to reach before writing the data to the underlying stream.

The default value is 128 KiB.

If set to 0 each message will be eagerly written to the underlying stream. It is often more optimal to allow them to buffer a little, hence the default value.

Note: flush will always fully write the buffer regardless.

fn max_write_buffer_size(self: Self, max: usize) -> Self

The max size of the write buffer in bytes. Setting this can provide backpressure in the case the write buffer is filling up due to write errors.

The default value is unlimited.

Note: The write buffer only builds up past write_buffer_size when writes to the underlying stream are failing. So the write buffer can not fill up if you are not observing write errors even if not flushing.

Note: Should always be at least write_buffer_size + 1 message and probably a little more depending on error handling strategy.

fn max_message_size(self: Self, max: usize) -> Self

Set the maximum message size (defaults to 64 megabytes)

fn max_frame_size(self: Self, max: usize) -> Self

Set the maximum frame size (defaults to 16 megabytes)

fn accept_unmasked_frames(self: Self, accept: bool) -> Self

Allow server to accept unmasked frames (defaults to false)

fn protocols<I>(self: Self, protocols: I) -> Self
where
    I: IntoIterator,
    <I as >::Item: Into<Cow<'static, str>>

Set the known protocols.

If the protocol name specified by Sec-WebSocket-Protocol header to match any of them, the upgrade response will include Sec-WebSocket-Protocol header and return the protocol name.

The protocols should be listed in decreasing order of preference: if the client offers multiple protocols that the server could support, the server will pick the first one in this list.

Examples

use axum::{
    extract::ws::{WebSocketUpgrade, WebSocket},
    routing::any,
    response::{IntoResponse, Response},
    Router,
};

let app = Router::new().route("/ws", any(handler));

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.protocols(["graphql-ws", "graphql-transport-ws"])
        .on_upgrade(|socket| async {
            // ...
        })
}
# let _: Router = app;
fn selected_protocol(self: &Self) -> Option<&HeaderValue>

Return the selected WebSocket subprotocol, if one has been chosen.

If [protocols()][Self::protocols] has been called and a matching protocol has been selected, the return value will be Some containing said protocol. Otherwise, it will be None.

fn on_failed_upgrade<C>(self: Self, callback: C) -> WebSocketUpgrade<C>
where
    C: OnFailedUpgrade

Provide a callback to call if upgrading the connection fails.

The connection upgrade is performed in a background task. If that fails this callback will be called.

By default any errors will be silently ignored.

Example

use axum::{
    extract::{WebSocketUpgrade},
    response::Response,
};

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.on_failed_upgrade(|error| {
        report_error(error);
    })
    .on_upgrade(|socket| async { /* ... */ })
}
#
# fn report_error(_: axum::Error) {}
fn on_upgrade<C, Fut>(self: Self, callback: C) -> Response
where
    C: FnOnce(WebSocket) -> Fut + Send + 'static,
    Fut: Future<Output = ()> + Send + 'static,
    F: OnFailedUpgrade

Finalize upgrading the connection and call the provided callback with the stream.

impl<F = DefaultOnFailedUpgrade> Freeze for WebSocketUpgrade<F>

impl<F> Debug for WebSocketUpgrade<F>

fn fmt(self: &Self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result

impl<F> RefUnwindSafe for WebSocketUpgrade<F>

impl<F> Send for WebSocketUpgrade<F>

impl<F> Sync for WebSocketUpgrade<F>

impl<F> Unpin for WebSocketUpgrade<F>

impl<F> UnwindSafe for WebSocketUpgrade<F>

impl<S> FromRequestParts for WebSocketUpgrade<DefaultOnFailedUpgrade>

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, <Self as >::Rejection>

impl<S, T> FromRequest for WebSocketUpgrade<F>

fn from_request(req: Request<Body>, state: &S) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

impl<T> Any for WebSocketUpgrade<F>

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for WebSocketUpgrade<F>

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for WebSocketUpgrade<F>

fn borrow_mut(self: &mut Self) -> &mut T

impl<T> From for WebSocketUpgrade<F>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Instrument for WebSocketUpgrade<F>

impl<T> Same for WebSocketUpgrade<F>

impl<T> WithSubscriber for WebSocketUpgrade<F>

impl<T, U> Into for WebSocketUpgrade<F>

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom for WebSocketUpgrade<F>

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto for WebSocketUpgrade<F>

fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>

impl<V, T> VZip for WebSocketUpgrade<F>

fn vzip(self: Self) -> V