2018-09-20 04:14:30 +00:00
|
|
|
#[macro_use] extern crate rocket;
|
|
|
|
|
2020-07-22 23:10:02 +00:00
|
|
|
use rocket::{Request, Data};
|
2020-07-05 18:35:36 +00:00
|
|
|
use rocket::local::blocking::Client;
|
2018-09-20 04:14:30 +00:00
|
|
|
use rocket::request::Form;
|
2020-07-12 09:23:00 +00:00
|
|
|
use rocket::data::{self, FromData};
|
2018-09-20 04:14:30 +00:00
|
|
|
use rocket::http::{RawStr, ContentType, Status};
|
2020-07-11 17:47:48 +00:00
|
|
|
use rocket::tokio::io::AsyncReadExt;
|
2018-09-20 04:14:30 +00:00
|
|
|
|
|
|
|
// Test that the data parameters works as expected.
|
|
|
|
|
|
|
|
#[derive(FromForm)]
|
|
|
|
struct Inner<'r> {
|
|
|
|
field: &'r RawStr
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Simple(String);
|
|
|
|
|
2020-07-12 09:23:00 +00:00
|
|
|
#[async_trait]
|
|
|
|
impl FromData for Simple {
|
2018-09-20 04:14:30 +00:00
|
|
|
type Error = ();
|
|
|
|
|
2020-07-12 09:23:00 +00:00
|
|
|
async fn from_data(_: &Request<'_>, data: Data) -> data::Outcome<Self, ()> {
|
|
|
|
let mut string = String::new();
|
|
|
|
let mut stream = data.open().take(64);
|
|
|
|
if let Err(_) = stream.read_to_string(&mut string).await {
|
2020-07-22 23:10:02 +00:00
|
|
|
return data::Outcome::Failure((Status::InternalServerError, ()));
|
2020-07-12 09:23:00 +00:00
|
|
|
}
|
2018-09-20 04:14:30 +00:00
|
|
|
|
2020-07-22 23:10:02 +00:00
|
|
|
data::Outcome::Success(Simple(string))
|
2018-09-20 04:14:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/f", data = "<form>")]
|
2019-06-13 01:59:25 +00:00
|
|
|
fn form(form: Form<Inner<'_>>) -> String { form.field.url_decode_lossy() }
|
2018-09-20 04:14:30 +00:00
|
|
|
|
|
|
|
#[post("/s", data = "<simple>")]
|
|
|
|
fn simple(simple: Simple) -> String { simple.0 }
|
|
|
|
|
2020-07-05 18:35:36 +00:00
|
|
|
#[test]
|
|
|
|
fn test_data() {
|
2018-09-20 04:14:30 +00:00
|
|
|
let rocket = rocket::ignite().mount("/", routes![form, simple]);
|
2020-07-05 18:35:36 +00:00
|
|
|
let client = Client::new(rocket).unwrap();
|
2018-09-20 04:14:30 +00:00
|
|
|
|
2020-06-22 11:54:34 +00:00
|
|
|
let response = client.post("/f")
|
2018-09-20 04:14:30 +00:00
|
|
|
.header(ContentType::Form)
|
|
|
|
.body("field=this%20is%20here")
|
2020-07-05 18:35:36 +00:00
|
|
|
.dispatch();
|
2018-09-20 04:14:30 +00:00
|
|
|
|
2020-07-05 18:35:36 +00:00
|
|
|
assert_eq!(response.into_string().unwrap(), "this is here");
|
2018-09-20 04:14:30 +00:00
|
|
|
|
2020-07-05 18:35:36 +00:00
|
|
|
let response = client.post("/s").body("this is here").dispatch();
|
|
|
|
assert_eq!(response.into_string().unwrap(), "this is here");
|
2018-09-20 04:14:30 +00:00
|
|
|
|
2020-07-05 18:35:36 +00:00
|
|
|
let response = client.post("/s").body("this%20is%20here").dispatch();
|
|
|
|
assert_eq!(response.into_string().unwrap(), "this%20is%20here");
|
2018-09-20 04:14:30 +00:00
|
|
|
}
|