expression
Axum: declare a bounded WebSocket upgrade
The upgrade extractor prepares a WebSocket connection. Limit both complete-message and frame sizes, and give the upgraded socket to an async handler. This in-memory request lacks upgrade headers and must be rejected; the handler is not executed. Real deployment additionally requires authentication, origin checks, deadlines and connection quotas. Standalone synthetic example. Expected stdout (not executed): missing upgrade rejected Common mistake: Treating ordinary HTTP requests as successfully upgraded or using this handler as production authentication.
Formal Syntax & Structure
rust syntaxrust
ws.max_message_size(n).max_frame_size(n).on_upgrade(handler)Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { async fn handle(mut socket: WebSocket) { let _ = socket.send(Message::Text("welcome".into())).await; } async fn upgrade(ws: WebSocketUpgrade) -> impl IntoResponse { ws.max_message_size(4096).max_frame_size(4096).on_upgrade(handle) } let app = Router::new().route("/ws", axum::routing::get(upgrade)); let res = app.oneshot(Request::builder().uri("/ws").body(Body::empty()).unwrap()).await.unwrap(); assert!(res.status().is_client_error()); println!("missing upgrade rejected");}