Skip to content

Commit ff87f21

Browse files
authored
Merge pull request #24 from yoshuawuyts/refactor-big-match-statement
refactor a big match statement on the server code
2 parents aec60c6 + 9bfd5eb commit ff87f21

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

src/server.rs

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -215,35 +215,22 @@ where
215215
req = req.set_header(header.name, std::str::from_utf8(header.value)?)?;
216216
}
217217

218-
// Process the body if `Content-Length` was passed.
219-
if let Some(content_length) = httparse_req
220-
.headers
221-
.iter()
222-
.find(|h| h.name.eq_ignore_ascii_case("Content-Length"))
223-
{
224-
let length = std::str::from_utf8(content_length.value)
225-
.ok()
226-
.and_then(|s| s.parse::<usize>().ok());
227-
228-
if let Some(len) = length {
229-
req = req.set_body_reader(reader);
230-
req = req.set_len(len);
231-
232-
Ok(Some(DecodedRequest::WithBody(req)))
233-
} else {
234-
return Err("Invalid value for Content-Length".into());
235-
}
236-
} else {
237-
Ok(Some(DecodedRequest::WithoutBody(req, Box::new(reader))))
238-
}
218+
// Check for content-length, that determines determines whether we can parse
219+
// it with a known length, or need to use chunked encoding.
220+
let len = match req.header("Content-Length") {
221+
Some(len) => len.parse::<usize>()?,
222+
None => return Ok(Some(DecodedRequest::WithoutBody(req, Box::new(reader)))),
223+
};
224+
req = req.set_body_reader(reader).set_len(len);
225+
Ok(Some(DecodedRequest::WithBody(req)))
239226
}
240227

241-
/// A decoded response
242-
///
243-
/// Either a request with body stream OR a request without a
244-
/// a body stream paired with the underlying stream
228+
/// A decoded request
245229
pub enum DecodedRequest {
230+
/// The TCP connection is inside the request already, so the lifetimes match up.
246231
WithBody(Request),
232+
/// The TCP connection is *not* inside the request body, so we need to pass
233+
/// it along with it to make the lifetimes match up.
247234
WithoutBody(Request, Box<dyn BufRead + Unpin + Send + 'static>),
248235
}
249236

0 commit comments

Comments
 (0)