Using RwLock in a Json #2131
-
I have the following handler function which works: async fn axum_handler(State(state): State<Arc<RwLock<Vec<i32>>>>) -> impl IntoResponse {
let lock = state.clone();
let val = lock.read().unwrap();
return Json(val.clone());
} Pro: Simple enough to implement Here I am returning Alternative 1async fn axum_handler(State(state): State<Arc<RwLock<Vec<i32>>>>) -> impl IntoResponse {
let lock = state.clone();
let val = lock.read().unwrap();
let serialized_data = serde_json::to_string(&*val).unwrap();
let mut headers = HeaderMap::new();
headers.insert("content-type", "application/json".parse().unwrap());
return (headers, serialized_data);
} Pro: No clone required Alternative 2async fn axum_handler(State(state): State<Arc<RwLock<Arc<Vec<i32>>>>>) -> impl IntoResponse {
let lock = state.clone();
let val = lock.read().unwrap().clone();
let val = Arc::into_inner(val).unwrap();
return Json(val);
} Pro: Simple enough as an alternative What I wantAn alternative that uses a very basic state with preferably no copies when returning it in a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You can use https://docs.rs/axum-extra/0.7.5/axum_extra/response/struct.ErasedJson.html You can also always make your own type that implements IntoResponse |
Beta Was this translation helpful? Give feedback.
You can use https://docs.rs/axum-extra/0.7.5/axum_extra/response/struct.ErasedJson.html
You can also always make your own type that implements IntoResponse