warp
warp copied to clipboard
Set cookies in responses
It would be great to have a filter that allows you to set cookies on responses. At the moment the work around is to set the Set-Cookie
header through the header APIs. However, this requires you to encode the cookie value manually, which is error-prone. In addition, this approach only allows you to set one cookie per response (#609).
This filter could also make it easy to "delete" cookies. Currently, I have to write code to set the cookie Expires
time to be in the past. Would be nice if this functionality was available off the shelf.
Edit: I'm a rust noob but would love to take a stab at this if someone could provide a little guidance!
This filter could also make it easy to "delete" cookies. Currently, I have to write code to set the cookie Expires time to be in the past. Would be nice if this functionality was available off the shelf.
Edit: I'm a rust noob but would love to take a stab at this if someone could provide a little guidance!
The server can only make a cookie expire to achieve the goal of deleting a cookie on the client side. The server cannot directly delete a client's cookie, but can only make it expire. Consider renaming "expiration" as "deletion" to reflect this.
It would be great to have a filter that allows you to set cookies on responses. At the moment the work around is to set the
Set-Cookie
header through the header APIs. However, this requires you to encode the cookie value manually, which is error-prone. In addition, this approach only allows you to set one cookie per response (#609).
Now it is possible to accomplish it using the Response from reply:
async fn response() -> Result<impl warp::Reply, warp::Rejection> {
// Serialization
let data = json!(r#"{"msg": "OK"}"#);
let data = data.to_string();
// Place the serialized data into the response body
let res = warp::reply::json(&data);
// Insert response headers
let res = warp::reply::with_header(res, "key", "value");
let res = warp::reply::with_header(res, "content-type", "application/json");
// Set cookies
let res = warp::reply::with_header(res, "set-cookie", "a=12345");
let res = warp::reply::with_header(res, "set-cookie", "b=67890");
// Set status code
let res = warp::reply::with_status(res, warp::http::StatusCode::BAD_REQUEST);
Ok(res)
}