How to append response headers to ServeFile? #1686
-
I went through various questions here, I spent hours in axum and tower code, and all I can conclude is that I can't simply modify response headers with Please tell me that I'm wrong and that I'm overlooking something, because I refuse to believe such fundamental functionality wouldn't be included. Please, don't tell me to open the file manually and convert it to There's a similar discussion here: #608 however that discussion ends exactly at the point where I'm picking this up. I'm becoming quite hopeless. Is there a way how to do it, without reimplementing the whole |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
You can use https://docs.rs/tower-http/0.3.5/tower_http/set_header/response/index.html or https://docs.rs/tower/0.4.13/tower/trait.ServiceExt.html#method.map_response to add additional headers to a response. |
Beta Was this translation helpful? Give feedback.
-
Thanks for posting this question and answer, it was a great starting point. The answer from 2023-01-08 not work for me anymore on axum 0.7.2. I ran into Send/Sync issues. Here is the static file where I need to add a header: .nest_service(
"/js/lib_worker.min.js",
ServeFile::new("../target/js/lib_worker.min.js").precompressed_br(),
) I first define a function to add the header to the response: async fn credentialless<B>(mut response: Response<B>) -> Response<B> {
response.headers_mut().insert("cross-origin-embedder-policy", "credentialless".parse().unwrap());
response
} Now I can do a similar trick as above, first putting the download service in a variable and then layering a See: https://docs.rs/axum/latest/axum/middleware/fn.map_response.html let download: routing::MethodRouter = routing::get_service(
ServeFile::new("../target/js/lib_worker.min.js").precompressed_br()
).layer(map_response(credentialless)); Finally, I can nest the download service in the router: .route_service(
"/js/lib_worker.min.js",
download,
) If anyone is curious about the "off topic" bits in the example:
|
Beta Was this translation helpful? Give feedback.
You can use https://docs.rs/tower-http/0.3.5/tower_http/set_header/response/index.html or https://docs.rs/tower/0.4.13/tower/trait.ServiceExt.html#method.map_response to add additional headers to a response.