actix / actix/actix-web

Allow different form submits on the same resource / Invalid route fails ungracefully

Aperta
#568 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub
C-improvement
Lingua principale
Rust
Stelle
24.8k
Fork
1.9k
Merge medio
23h 10m
PR unite (30g)
26

Descrizione

Hey, first I want to thank you for your great work. Maybe there's a simple solution to this that i missed.

1. I would like to handle multiple/different forms on the same URL.

2. If you submit form 2, it seems that the first POST resource (form1) is chosen and then fails ungracefully to execute (because struct Form1 does not match the POST data). If a route is chosen, it should always be able to execute it, don't you think so, too?

3. Is there a way to forward all POST data to the called function so that I can handle it on my own?

**Relevance:**
If parts of the Form depend on the user's selections (dynamically created Form fields), you cannot know beforehand which data will be sent to the server.

**Example:**

```rust
extern crate actix_web;

#[macro_use]
extern crate serde_derive;

use actix_web::{
http, middleware, server, App, Error, Form, HttpRequest, HttpResponse, Result, State,
};

struct AppState {}

#[derive(Deserialize)]
pub struct Form1 {
test1: String,
}
#[derive(Deserialize)]
pub struct Form2 {
test2: String,
}

fn get(_state: State) -> Result {
//println!("index::get.state = {}", _state);
Ok(HttpResponse::build(http::StatusCode::OK)
.content_type("text/html")
.body(
"Form1:



Form2:

",
))
}

fn post_form1((req, form): (HttpRequest, Form)) -> Result {
println!("Handling form1: {:?}", req);
Ok(HttpResponse::build(http::StatusCode::OK)
.content_type("text/html")
.body(format!("Form1.test1 = {}", form.test1)))
}

fn post_form2((req, form): (HttpRequest, Form)) -> Result {
println!("Handling form2: {:?}", req);
Ok(HttpResponse::build(http::StatusCode::OK)
.content_type("text/html")
.body(format!("Form2.test2 = {}", form.test2)))
}

fn error_404(_state: State) -> Result {
Ok(HttpResponse::build(http::StatusCode::OK)
.content_type("text/plain")
.body(format!("Eww! That's a 404.")))
}

fn main() {
server::new(|| {
App::with_state(AppState {})
// enable logger
.middleware(middleware::Logger::default())
.resource("/", |r| {
r.method(http::Method::GET).with(get);

// works properly unless you use form2 (which results in a blank page)
r.method(http::Method::POST).with(post_form1);

// will never be called
r.method(http::Method::POST).with(post_form2);
})
.default_resource(|r| r.with(error_404))
})
.bind("127.0.0.1:8080")
.unwrap()
.run();
}

```

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.