Skip to content

How to make middleware which will return HTML/JSON #323

Answered by davidpdrsn
Umenokin asked this question in Q&A
Discussion options

You must be logged in to vote

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>;

axum::body::BoxBody is a type erased body that allows you to merge different body types into one. You can convert a body into a BoxBody with axum::body::box_body. Something like this:

let bytes: Vec<u8> = "hello, world!\n"
     as_bytes()
    .to_owned();

let res = Response::builder()
    .status(200)
    .h…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@Umenokin
Comment options

Comment options

You must be logged in to vote
1 reply
@Umenokin
Comment options

Answer selected by Umenokin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants