Skip to content

Commit

Permalink
Merge pull request #169 from robertwayne/axum-example-fix
Browse files Browse the repository at this point in the history
Corrected route matching on axum example
  • Loading branch information
Peter John committed Feb 9, 2022
2 parents 7ab0590 + 2846da9 commit 74a3e07
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions examples/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,42 +11,47 @@ use std::net::SocketAddr;

#[tokio::main]
async fn main() {
// build our application with a route
// Define our app routes, including a fallback option for anything not matched.
let app = Router::new()
.route("/hello", get(helloworld))
// handle static files with rust_embed
.route("/", get(index_handler))
.route("/index.html", get(index_handler))
.route("/dist/", static_handler.into_service())
.fallback(static_handler.into_service());
.route("/dist/*file", static_handler.into_service())
.fallback(get(not_found));

// run it
// Start listening on the given address.
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("listening on {}", addr);
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
}

async fn helloworld() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}

// serve index.html from examples/public/index.html
// We use static route matchers ("/" and "/index.html") to serve our home
// page.
async fn index_handler() -> impl IntoResponse {
static_handler("/index.html".parse::<Uri>().unwrap()).await
}

// static_handler is a handler that serves static files from the
// We use a wildcard matcher ("/dist/*file") to match against everything
// within our defined assets directory. This is the directory on our Asset
// struct below, where folder = "examples/public/".
async fn static_handler(uri: Uri) -> impl IntoResponse {
let mut path = uri.path().trim_start_matches('/').to_string();

if path.starts_with("dist/") {
path = path.replace("dist/", "");
}

StaticFile(path)
}

// Finally, we use a fallback route for anything that didn't match.
async fn not_found() -> Html<&'static str> {
Html("<h1>404</h1><p>Not Found</p>")
}

#[derive(RustEmbed)]
#[folder = "examples/public/"]
struct Asset;

pub struct StaticFile<T>(pub T);

impl<T> IntoResponse for StaticFile<T>
Expand All @@ -55,6 +60,7 @@ where
{
fn into_response(self) -> Response {
let path = self.0.into();

match Asset::get(path.as_str()) {
Some(content) => {
let body = boxed(Full::from(content.data));
Expand Down

0 comments on commit 74a3e07

Please sign in to comment.