Search code examples
rustrust-axum

How can I return a header and string body inline when defining axum router?


I currently have this working:

let app = Router::new()
    .route("/foo.js", get(foo_js))
    ...
async fn foo_js() -> impl IntoResponse {
    ([(header::CONTENT_TYPE, "text/javascript")], FOO_JS_CONTENT)
}

But I have a small number of static files which I want to be embedded in the server binary. A separate function for each one seems like overkill.

I've tried to save some indirection by doing it inline but I get an error:

let app = Router::new()
    .route("/foo.js", get(|| -> impl IntoResponse {([(header::CONTENT_TYPE, "text/javascript")], FOO_JS_CONTENT)}))
    ....
error[E0562]: `impl Trait` only allowed in function and inherent method return types, not in closure return types
  --> src/main.rs:12:19
   |
12 |         get(|| -> impl IntoResponse {([(header::CONTENT_TYPE, "text/javascript")], FOO_JS_CONTENT)}),
   |                   ^^^^^^^^^^^^^^^^^

How can I serve a static string with a content-type header from Axum?


Solution

  • You can do it like this:

    let app = Router::new()
        .route("/foo.js", get(|| async {
            ([(header::CONTENT_TYPE, "text/javascript")], "some_foo_js")
        }));