From 7a53882738a1fb90e03439d85f21ad67331bf93e Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Wed, 4 Feb 2026 18:31:05 +0900 Subject: [PATCH] form: add an example of optional forms --- docs/extractors.md | 4 ++++ examples/extractors/src/form_optional.rs | 27 ++++++++++++++++++++++++ examples/extractors/src/main.rs | 1 + 3 files changed, 32 insertions(+) create mode 100644 examples/extractors/src/form_optional.rs diff --git a/docs/extractors.md b/docs/extractors.md index 869d0c6e..7567816d 100644 --- a/docs/extractors.md +++ b/docs/extractors.md @@ -63,6 +63,10 @@ A URL-encoded form body can be extracted to a struct, much like `Json`. This +If the form body is optional, or you want to handle invalid input yourself, wrap the extractor in `Option` and check for `None` in your handler. + + + ## Other Actix Web also provides many other extractors, here's a few important ones: diff --git a/examples/extractors/src/form_optional.rs b/examples/extractors/src/form_optional.rs new file mode 100644 index 00000000..49ac7cc6 --- /dev/null +++ b/examples/extractors/src/form_optional.rs @@ -0,0 +1,27 @@ +// +use actix_web::{post, web, App, HttpServer, Result}; +use serde::Deserialize; + +#[derive(Deserialize)] +struct FormData { + username: String, +} + +/// accept form data when it is present and valid +#[post("/maybe")] +async fn maybe(form: Option>) -> Result { + let Some(form) = form else { + return Ok("Missing or invalid form data.".to_string()); + }; + + Ok(format!("Welcome {}!", form.username)) +} +// + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + HttpServer::new(|| App::new().service(maybe)) + .bind(("127.0.0.1", 8080))? + .run() + .await +} diff --git a/examples/extractors/src/main.rs b/examples/extractors/src/main.rs index 23bebefc..f8c4a623 100644 --- a/examples/extractors/src/main.rs +++ b/examples/extractors/src/main.rs @@ -3,6 +3,7 @@ use serde::Deserialize; // pub mod custom_handler; pub mod form; +pub mod form_optional; pub mod json_one; pub mod json_two; pub mod multiple;