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
103
104
105
use std::error;
use std::fmt;
use Request;
use RequestBody;
use multipart::server::Multipart as InnerMultipart;
pub use multipart::server::MultipartField;
pub use multipart::server::MultipartData;
#[derive(Clone, Debug)]
pub enum MultipartError {
WrongContentType,
BodyAlreadyExtracted,
}
impl error::Error for MultipartError {
#[inline]
fn description(&self) -> &str {
match *self {
MultipartError::WrongContentType => {
"the `Content-Type` header of the request indicates that it doesn't contain \
multipart data or is invalid"
},
MultipartError::BodyAlreadyExtracted => {
"can't parse the body of the request because it was already extracted"
},
}
}
}
impl fmt::Display for MultipartError {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "{}", error::Error::description(self))
}
}
pub fn get_multipart_input(request: &Request) -> Result<Multipart, MultipartError> {
let boundary = match multipart_boundary(request) {
Some(b) => b,
None => return Err(MultipartError::WrongContentType)
};
let request_body = if let Some(body) = request.data() {
body
} else {
return Err(MultipartError::BodyAlreadyExtracted);
};
Ok(Multipart {
inner: InnerMultipart::with_body(request_body, boundary)
})
}
pub struct Multipart<'a> {
inner: InnerMultipart<RequestBody<'a>>
}
impl<'a> Multipart<'a> {
pub fn next(&mut self) -> Option<MultipartField<&mut InnerMultipart<RequestBody<'a>>>> {
self.inner.read_entry().unwrap_or(None)
}
}
fn multipart_boundary(request: &Request) -> Option<String> {
const BOUNDARY: &str = "boundary=";
let content_type = match request.header("Content-Type") {
None => return None,
Some(c) => c
};
let start = match content_type.find(BOUNDARY) {
Some(pos) => pos + BOUNDARY.len(),
None => return None
};
let end = content_type[start..].find(';').map_or(content_type.len(), |end| start + end);
Some(content_type[start .. end].to_owned())
}