How to make middleware which will return HTML/JSON #323
-
Hi everyone. But I am struggling to adjust it to return HTML right away. I am trying different variations of which, let me post the simplest one:
The error I am getting is:
I understand that it is related to rust's generic types below:
So, now, how can I update |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I'm not sure that I understood right your use case, but it looks like that you need service, which will accept any request instead of middleware. Look at this example https://docs.rs/axum/0.2.4/axum/#routing-to-any-service. |
Beta Was this translation helpful? Give feedback.
-
By declaring your middleware with type Response = S::Response; You're saying that it returns exactly the same type of response that the middleware it is wrapping returns. However if you want to return a different kind of response that isn't possible, because there is no way to generically construct the response. You can change the type to type Response = Response<axum::body::BoxBody>;
let bytes: Vec<u8> = "hello, world!\n"
as_bytes()
.to_owned();
let res = Response::builder()
.status(200)
.header("X-Custom-Foo", "Bar")
.body(axum::body::box_body(axum::body::Full::from(bytes))
.unwrap();
// res is now a `Response<axum::body::BoxBody>` You can convert the response from the inner service in a similar way: let response = inner_service.call(request).await?.map(axum::body::box_body); Let me know if that made things more clear 😊 |
Beta Was this translation helpful? Give feedback.
By declaring your middleware with
You're saying that it returns exactly the same type of response that the middleware it is wrapping returns. However if you want to return a different kind of response that isn't possible, because there is no way to generically construct the response.
You can change the type to
axum::body::BoxBody
is a type erased body that allows you to merge different body types into one. You can convert a body into aBoxBody
withaxum::body::box_body
. Something like this: