Expand description
Flash messages and redirects (18.35.0, #94): a message set on one response — usually a redirect after a form post — and shown on the next page, once.
use rust_web_server::app::App;
use rust_web_server::error::IntoResponse;
use rust_web_server::extract::FromRequest;
use rust_web_server::flash::{Flash, FlashLayer, Redirect};
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
use rust_web_server::test_client::TestClient;
let app = App::with_state(())
.post("/posts", |_, _, _, _| Redirect::to("/posts").notice("Post saved").into_response())
.get("/posts", |request, _, _, _| {
let flash = Flash::from_request(request).unwrap();
Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, flash.notice().unwrap_or(""))
})
.wrap(FlashLayer::new());
let client = TestClient::new(app);
let saved = client.post("/posts").send();
assert_eq!(303, saved.status());The messages travel in the rws_flash cookie (HttpOnly,
SameSite=Lax, Path=/), percent-encoded: readable and changeable by
the browser, so never put anything in a flash that the page trusts —
templates escape it like any other text. FlashLayer removes the
cookie from the browser after the request that carried it, unless the
response sets a new flash. A flash cookie is capped at
MAX_COOKIE_BYTES; messages past it are dropped.
Structs§
- Flash
- The flash messages a request carried. A handler argument
(
FromRequest, never fails); empty when there are none. - Flash
Layer - Removes the flash cookie after the request that carried it, unless the
response sets a new flash. Wrap the app in it once:
app.wrap(FlashLayer::new()). - Flash
Message - One message: its kind (
notice,alert, or your own) and its text. - Redirect
- A redirect, optionally with flash messages:
303 See Otherby default (the method after a form post becomesGET).
Constants§
- COOKIE_
NAME - The cookie flash messages travel in.
- MAX_
COOKIE_ BYTES - The largest flash cookie value written; later messages are dropped.
Functions§
- set
- Add a flash message to
response(after any it already sets).