fix: allow SSE server router to be nested (#240)
* fix: allow SSE server router to be nested
This commit is contained in:
parent
97bb4796dd
commit
47518b3906
1 changed files with 77 additions and 27 deletions
|
|
@ -1,8 +1,8 @@
|
|||
use std::{collections::HashMap, io, net::SocketAddr, sync::Arc, time::Duration};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
Extension, Json, Router,
|
||||
extract::{NestedPath, Query, State},
|
||||
http::{StatusCode, request::Parts},
|
||||
response::{
|
||||
Response,
|
||||
|
|
@ -84,6 +84,7 @@ async fn post_event_handler(
|
|||
|
||||
async fn sse_handler(
|
||||
State(app): State<App>,
|
||||
nested_path: Option<Extension<NestedPath>>,
|
||||
parts: Parts,
|
||||
) -> Result<Sse<impl Stream<Item = Result<Event, io::Error>>>, Response<String>> {
|
||||
let session = session_id();
|
||||
|
|
@ -115,12 +116,13 @@ async fn sse_handler(
|
|||
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
return Err(response);
|
||||
}
|
||||
let nested_path = nested_path.as_deref().map(NestedPath::as_str).unwrap_or("");
|
||||
let post_path = app.post_path.as_ref();
|
||||
let ping_interval = app.sse_ping_interval;
|
||||
let stream = futures::stream::once(futures::future::ok(
|
||||
Event::default()
|
||||
.event("endpoint")
|
||||
.data(format!("{post_path}?sessionId={session}")),
|
||||
.data(format!("{nested_path}{post_path}?sessionId={session}")),
|
||||
))
|
||||
.chain(ReceiverStream::new(to_client_rx).map(|message| {
|
||||
match serde_json::to_string(&message) {
|
||||
|
|
@ -257,8 +259,6 @@ impl SseServer {
|
|||
Ok(sse_server)
|
||||
}
|
||||
|
||||
/// Warning: This function creates a new SseServer instance with the provided configuration.
|
||||
/// `App.post_path` may be incorrect if using `Router` as an embedded router.
|
||||
pub fn new(config: SseServerConfig) -> (SseServer, Router) {
|
||||
let (app, transport_rx) = App::new(
|
||||
config.post_path.clone(),
|
||||
|
|
|
|||
Loading…
Reference in a new issue