-
SummaryGiven a state like struct AppState<G: Greeter> {
greeter: G,
} Is it at all possible to have handlers that extract the async fn handler<G: Greeter>(State(greeter): State<G>) -> /* ... */ axum version0.7.5 |
Beta Was this translation helpful? Give feedback.
Answered by
mhutter
Jul 2, 2024
Replies: 2 comments 1 reply
-
Yes, this should be possible by writing an app.route("/path", get(handler::<TypeThatImplementsHandler>)) |
Beta Was this translation helpful? Give feedback.
1 reply
-
Okay, I figured it out. While I was on the right track, what was missing was a trait bound So this works: // Trait & Implementations
trait Greeter: Clone + Send + Sync + 'static { /* ... */ }
impl Greeter for WorldGreeter { /* ... */ }
impl Greeter for UniverseGreeter { /* ... */ }
// Handler that uses Greeter
async fn homepage<G: Greeter>(State(greeter): State<G>) -> { /* ... */ }
// AppState that contains Greeter
struct AppState<G: Greeter> {
greeter: G,
}
// FromRef implementations
impl FromRef<AppState<UniverseGreeter>> for UniverseGreeter { /* ... */ }
impl FromRef<AppState<WorldGreeter>> for WorldGreeter { /* ... */ }
// Putting it all together
async fn run_app<G>(greeter: G)
where
G: Greeter + FromRef<AppState<G>>, // <--- I was missing FromRef<...> here!
{
let state = AppState { greeter };
let app = Router::new()
.route("/", get(homepage::<G>))
.with_state(state);
/* ... */
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
mhutter
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay, I figured it out.
While I was on the right track, what was missing was a trait bound
X: AsRef<AppState<X>>
.So this works: