Search code examples
rustrust-tokiorust-axum

How to get the query prameters when accepting a websocket connection using axum?


How do I get the query parameters when accepting a websocket connection using axum?

The following code is used to accept a websocket connection, but how can I get the parameters of the url?

// Echo back
async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let msg = if let Ok(msg) = msg {
            msg
        } else {
            // client disconnected
            return;
        };

        if socket.send(msg).await.is_err() {
            // client disconnected
            return;
        }
    }
}

async fn ws_handle(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

    let app = Router::new()
        .route("/ws", get(ws_handle));

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();

For example, I access via wscat ws://127.0.0.1:3000/ws?name=aaa&age=18 and want to get the name and age fetch values.


Solution

  • You can use other extractors alongside WebSocketUpgrade. You'd be looking for Query:

    use axum::extract::Query;
    use serde::Deserialize;
    
    #[derive(Deserialize)]
    struct Params {
        name: String,
        age: i32,
    }
    
    async fn ws_handle(
        Query(params): Query<Params>,
        ws: WebSocketUpgrade,
    ) -> Response {
        // do something with `params`
    
        ws.on_upgrade(handle_socket)
    }