英文:
for axum, how to set a header for a handler
问题
我找不到如何为响应设置标题的方法。
我已经查找了如何做到这一点,但没有找到一个直接的方法。
特别强调content-type
标头,如何从响应处理程序中设置标准和自定义标头,同时记住我已经可以执行thing.into_response()
。
英文:
I can't seem to find how to set a header for the response.
I have looked for how to do this but haven't found a straightforward way to do this.
With specific emphasis on the content-type
header, How to set both a standard & custom headers from a response handler bearing in mind that I can already do thing.into_response()
.
答案1
得分: 2
以下是您如何在处理程序中设置自定义响应头的示例代码:
use axum::http::HeaderMap;
use axum::response::IntoResponse;
async fn my_handler() -> impl IntoResponse {
let mut headers = HeaderMap::new();
headers.insert("x-my-hdr", "abc".parse().unwrap());
(headers, "It works!")
}
我已经测试了上述代码,包括自定义头部和标准头部(例如 Content-Type
),似乎在两种情况下都可以正常工作。
英文:
Here is an example how you can set a custom response header in your handler:
use axum::http::HeaderMap;
use axum::response::IntoResponse;
async fn my_handler() -> impl IntoResponse {
let mut headers = HeaderMap::new();
headers.insert("x-my-hdr", "abc".parse().unwrap());
(headers, "It works!")
}
I've tested the above with both custom and standard headers (such as Content-Type
) and it seems to work in both cases.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论