for axum, how to set a header for a handler

huangapple go评论119阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月26日 22:51:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定