我想编写一个返回impl Reply
的函数,即一个Warp处理程序。该函数执行一些业务逻辑,然后应返回两个 Set-Cookie
header ;每个 cookie 的内容都是不同的,并且取决于业务逻辑。我一直在使用这样的模式:
async fn my_handler() -> anyhow::Result<impl Reply> {
// Some business logic...
let reply = warp::reply::json(&json!({}));
let reply = warp::reply::with_status(reply, StatusCode::OK);
let reply = warp::reply::with_header(
reply,
header::SET_COOKIE,
"foo=bar",
);
Ok(warp::reply::with_header(
reply,
header::SET_COOKIE,
"baz=qux",
))
}
但是,这将导致仅设置第二个 cookie。单独有warp::filters::reply::headers
,最初似乎是我想要的,但目前还不清楚这如何与上面的 reply
配合得很好。
最佳答案
我可以通过将回复
转换为响应
然后手动操作响应来解决这个问题。这与 cperez08 的答案类似,但允许将两个相同名称的 header 附加到响应中:
async fn my_handler() -> anyhow::Result<impl Reply> {
// Some business logic...
let reply = warp::reply::json(&json!({}));
let reply = warp::reply::with_status(reply, StatusCode::OK);
// Set multiple e.g. cookies.
let mut cookies = HeaderMap::new();
cookies.append(header::SET_COOKIE, HeaderValue::from_str("foo").unwrap());
cookies.append(header::SET_COOKIE, HeaderValue::from_str("bar").unwrap());
// Convert `reply` into a `Response` so we can extend headers.
let mut response = reply.into_response();
let headers = response.headers_mut();
headers.extend(cookies);
Ok(response)
}
关于rust - 如何将两个同名的 header 附加到 Warp `Reply` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62964013/