As we can see above, the code for setting a MIME type is generic and doesn’t need anything except a Response to modify. It is therefore a prime AfterMiddleware candidate, which once implemented will remove the need for the code repetition in each and every one of our routes’ handlers. Here’s a very brief AfterMiddleware description from the docs:

AfterMiddleware receive both a Request and a Response and are responsible for doing any response post-processing.

Writing the middleware

As the docs said, AfterMiddleware receives both the Request and the Response. We don’t need to do anything to the Request so we’ll just mark it as unused with _. We do however want to modify the Response which can be done very straightforwardly with .set_mut(). Pieced together, we end up with this: