rustrust-axum

Returning a content-type and String directly from a .get() in Axum


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)
}

for a small number of static files which I want to be embedded in the server binary.

I would like to save some indirection and do something like:

    let app = Router::new()
        .route("/foo.js", get((([(header::CONTENT_TYPE, "text/javascript")], FOO_JS_CONTENT))))

I've tried:

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

but get:

error[E0562]: `impl Trait` only allowed in function and inherent method return types, not in closure return types
  --> src/main.rs:46:37
   |
46 | ...   .route("/foo.js", get(|| -> impl IntoResponse {([(header::CONTENT_TYPE, "text/javascr...
   |        

(I may also be missing an async on the closure, but this appears to be an experimental feature.)

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


Solution

  • Do you mean something like this?

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