-
SummaryHi, I want to do virtual hosting with Axum and I found https://github.com/skerkour/kerkour.com/tree/main/blog/2022/rust_axum_hostname_router/src which works with the latest Axum however I understand that the recommended way of adding state is with with_state. When I try this it fails to compile with the message:
Code here Can anyone help me solve this? Also it seems like a common enough requirement that it would be great to add as an example. By the way the original example doesnt work completely correctly as the host extractor includes the port as well. axum version0.7.5 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You're supplying the state at the wrong place. |
Beta Was this translation helpful? Give feedback.
-
Thanks to @jplatte I figured out one way to create virtual hosts in Axum. In Cargo.toml add the steer feature of tower
Define routers for each virtual host, and for each one call with_state, as shown in previous comment. Define the virtual host service that selects which router to use based on the host header, and/or forwarded headers (not shown)
This code could be more sophisticated by defining a struct for each Virtual host, that make sure you cant get the indices mixed up, by for example inserting more virtual hosts or changing the order in the vec. However, you probably want to do some fairly custom code for each virtual host like matching on subdomains or accepting www.example.com and example.com anyway, in any case this code is more of a how to than production code. Use the router, note any common routes can be defined here. (In the test case I had the type of the router had to be defined as Router<()> however it may not always be necessary.)
|
Beta Was this translation helpful? Give feedback.
You're supplying the state at the wrong place.
api_router
andwebsite_router
's handler need access to it, notapp
. When usingnest
, the required state type is automatically propagated to the parent router (if there are no conflicting requirements), but that only works fornest
, not thisoneshot
-based router nesting that you're doing.