Skip to content

Commit 90e9717

Browse files
authored
Merge pull request #65 from http-rs/simplify-server-loop
Simplify the main server loop
2 parents f19ec42 + 7fa1ce9 commit 90e9717

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

src/server.rs

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -30,36 +30,32 @@ where
3030
F: Fn(Request) -> Fut,
3131
Fut: Future<Output = http_types::Result<Response>>,
3232
{
33-
// TODO: make configurable
33+
// TODO: make these values configurable
3434
let timeout_duration = Duration::from_secs(10);
3535
const MAX_REQUESTS: usize = 200;
3636
let mut num_requests = 0;
3737

38-
// Decode a request. This may be the first of many since the connection is Keep-Alive by default.
39-
let r = io.clone();
40-
let req = decode(addr, r).await?;
41-
42-
if let Some(mut req) = req {
43-
loop {
44-
match num_requests {
45-
MAX_REQUESTS => return Ok(()),
46-
_ => num_requests += 1,
47-
};
48-
49-
// TODO: what to do when the endpoint returns Err
50-
let res = endpoint(req).await?;
51-
let mut encoder = Encoder::encode(res);
52-
io::copy(&mut encoder, &mut io).await?;
53-
54-
// Decode a new request, timing out if this takes longer than the
55-
// timeout duration.
56-
req = match timeout(timeout_duration, decode(addr, io.clone())).await {
57-
Ok(Ok(Some(r))) => r,
58-
Ok(Ok(None)) | Err(TimeoutError { .. }) => break, /* EOF or timeout */
59-
Ok(Err(e)) => return Err(e).into(),
60-
};
61-
// Loop back with the new request and stream and start again
62-
}
38+
loop {
39+
// Stop parsing requests if we exceed the threshold.
40+
match num_requests {
41+
MAX_REQUESTS => return Ok(()),
42+
_ => num_requests += 1,
43+
};
44+
45+
// Decode a new request, timing out if this takes longer than the
46+
// timeout duration.
47+
let req = match timeout(timeout_duration, decode(addr, io.clone())).await {
48+
Ok(Ok(Some(r))) => r,
49+
Ok(Ok(None)) | Err(TimeoutError { .. }) => break, /* EOF or timeout */
50+
Ok(Err(e)) => return Err(e).into(),
51+
};
52+
53+
// Pass the request to the endpoint and encode the response.
54+
let res = endpoint(req).await?;
55+
let mut encoder = Encoder::encode(res);
56+
57+
// Stream the response to the writer.
58+
io::copy(&mut encoder, &mut io).await?;
6359
}
6460

6561
Ok(())

0 commit comments

Comments
 (0)