【问题标题】:How to add custom headers to content::JSON in Rocket?如何在 Rocket 中向 content::JSON 添加自定义标头?
【发布时间】:2021-12-23 00:19:40
【问题描述】:

假设我在 rocket (v. 0.5.0-rc.1) 中有这个路由处理程序:

#[get("/route")]
pub async fn my_route() -> content::Json<String> {
    let json =
        rocket::serde::json::serde_json::to_string(&my_data).unwrap();
    content::Json(json)
}

如何在响应中添加另一个标头(content-type: application/json 除外)?

我想过这样的事情,但它不起作用:

#[get("/route")]
pub async fn my_route() -> content::Json<String> {
    let json =
        rocket::serde::json::serde_json::to_string(&my_data).unwrap();
    let mut content = content::Json(json);
    content.set_raw_header("Cache-Control", "max-age=120");
    content
}

我可以使用原始 rocket::Response 并自己设置 content-type: application/json 标头,但我无法弄清楚如何从可变长度字符串设置正文而不遇到生命周期问题。

【问题讨论】:

  • 在文档中 (rocket.rs/v0.4/guide/responses) 他们说要使用 use rocket::response::content; ... fn json() -&gt; content::Json&lt;&amp;'static str&gt;

标签: rust rust-rocket


【解决方案1】:

您可以像这样使用 JSON 字符串获得原始响应:

let json =
    rocket::serde::json::serde_json::to_string(&[1, 2, 3]).unwrap();
let response = Response::build()
    .header(ContentType::JSON)
    .raw_header("Cache-Control", "max-age=120")
    .sized_body(json.len(), Cursor::new(json))
    .finalize();

【讨论】:

  • 这引导我走上正确的道路。我必须定义一个结构,为其实现 Responder 特征,然后在 respond_to(self, _request: &amp;'r rocket::Request&lt;'_&gt;) -&gt; rocket::response::Result&lt;'static&gt; { 函数中构建响应。
猜你喜欢
  • 1970-01-01
  • 2019-09-12
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多