forked from seanmonstar/warp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultipart.rs
102 lines (87 loc) · 2.91 KB
/
multipart.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#![deny(warnings)]
use bytes::BufMut;
use futures_util::{TryFutureExt, TryStreamExt};
use warp::{multipart, Filter};
#[tokio::test]
async fn form_fields() {
let _ = pretty_env_logger::try_init();
let route = multipart::form().and_then(|form: multipart::FormData| {
async {
// Collect the fields into (name, value): (String, Vec<u8>)
let part: Result<Vec<(String, Vec<u8>)>, warp::Rejection> = form
.and_then(|part| {
let name = part.name().to_string();
let value = part.stream().try_fold(Vec::new(), |mut vec, data| {
vec.put(data);
async move { Ok(vec) }
});
value.map_ok(move |vec| (name, vec))
})
.try_collect()
.await
.map_err(|e| {
panic!("multipart error: {:?}", e);
});
part
}
});
let boundary = "--abcdef1234--";
let body = format!(
"\
--{0}\r\n\
content-disposition: form-data; name=\"foo\"\r\n\r\n\
bar\r\n\
--{0}--\r\n\
",
boundary
);
let req = warp::test::request()
.method("POST")
.header("content-length", body.len())
.header(
"content-type",
format!("multipart/form-data; boundary={}", boundary),
)
.body(body);
let vec = req.filter(&route).await.unwrap();
assert_eq!(&vec[0].0, "foo");
assert_eq!(&vec[0].1, b"bar");
}
#[tokio::test]
async fn max_length_is_enforced() {
let _ = pretty_env_logger::try_init();
let route = multipart::form()
.and_then(|_: multipart::FormData| async { Ok::<(), warp::Rejection>(()) });
let boundary = "--abcdef1234--";
let req = warp::test::request()
.method("POST")
// Note no content-length header
.header("transfer-encoding", "chunked")
.header(
"content-type",
format!("multipart/form-data; boundary={}", boundary),
);
// Intentionally don't add body, as it automatically also adds
// content-length header
let resp = req.filter(&route).await;
assert!(resp.is_err());
}
#[tokio::test]
async fn max_length_can_be_disabled() {
let _ = pretty_env_logger::try_init();
let route = multipart::form()
.max_length(None)
.and_then(|_: multipart::FormData| async { Ok::<(), warp::Rejection>(()) });
let boundary = "--abcdef1234--";
let req = warp::test::request()
.method("POST")
.header("transfer-encoding", "chunked")
.header(
"content-type",
format!("multipart/form-data; boundary={}", boundary),
);
// Intentionally don't add body, as it automatically also adds
// content-length header
let resp = req.filter(&route).await;
assert!(resp.is_ok());
}