-
Hi 👋 😃
Thank you for your help and also for the really cool crate! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi ! You have to wrap your state in an Here is an example with a custom use axum::routing::post;
use socketioxide::{
extract::{Data, SocketRef, State},
SocketIo,
};
use tokio::net::TcpListener;
use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;
use tracing::info;
use tracing_subscriber::FmtSubscriber;
#[derive(Clone)]
struct State {
messages: Arc<state::MessageStore>,
io: SocketIo,
}
async fn handler(axum::extract::State(State { messages, .. }): axum::extract::State<State>) {
dbg!(&messages); // You can use message store here !
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let messages = Arc::new(state::MessageStore::default());
let (layer, io) = SocketIo::builder().with_state(messages).build_layer();
let state = State {
messages,
io,
};
let app = axum::Router::new()
.route("/", post(handler))
.with_state(state)
.layer(
ServiceBuilder::new()
.layer(layer),
);
info!("Starting server");
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Ok(())
} |
Beta Was this translation helpful? Give feedback.
-
Thank you very much! ❤️ |
Beta Was this translation helpful? Give feedback.
Hi ! You have to wrap your state in an
Arc<T>
so that it is cheaply cloneable and that you have a reference in the state anywhere (it is required by axum and will soon be required by socketioxide also).Then you can either create your own axum
State
struct and put your socket.ioArc<SocketIoState>
in it or you can directly use the state you set for socket.io as an axum state:Here is an example with a custom
State
structs that wrapsstore::Messages
andSocketIo
.