Making a generic router #2184
-
I'm trying to create a generic function ( // Where Account and Post are structs that implement Resource:
fn router() -> Router {
Router::new()
.nest("/accounts", resource_router::<Account>)
.nest("/posts", resource_router::<Post>)
} Here is a minimal reproduction of the error I'm encountering: use axum::{Router, routing::get, Json};
use serde::{de::DeserializeOwned, Deserialize};
trait Resource: DeserializeOwned {}
#[derive(Deserialize)]
struct Account {
email: String,
}
impl Resource for Account {}
fn resource_router<R: Resource>() -> Router {
Router::new().route("/", get(get_resource::<R>))
}
async fn get_resource<R: Resource>(Json(_payload): Json<R>) {
todo!()
} And the error message:
I tried using
I've found that the error vanishes if I make any of the following changes:
So my guess is that the Json extractor isn't meeting the Any help would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You need to also make sure that trait Resource: DeserializeOwned + Send + 'static {}
fn resource_router<R: Resource>() -> Router {
Router::new().route("/", get(get_resource::<R>))
}
async fn get_resource<R: Resource>(_: Json<R>) {} The |
Beta Was this translation helpful? Give feedback.
You need to also make sure that
R
isSend + 'static
:The
Send
bound comes from the impl forHandler
for functions that take one argument:and the
'static
bound comes fromget
: