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
use std::time::Duration;
use async_std::future::{timeout, Future, TimeoutError};
use async_std::io::{self};
use async_std::io::{Read, Write};
use http_types::{Request, Response};
mod decode;
mod encode;
pub use decode::decode;
pub use encode::Encoder;
#[derive(Debug, Clone)]
pub struct ServerOptions {
headers_timeout: Option<Duration>,
}
impl Default for ServerOptions {
fn default() -> Self {
Self {
headers_timeout: Some(Duration::from_secs(60)),
}
}
}
pub async fn accept<RW, F, Fut>(io: RW, endpoint: F) -> http_types::Result<()>
where
RW: Read + Write + Clone + Send + Sync + Unpin + 'static,
F: Fn(Request) -> Fut,
Fut: Future<Output = http_types::Result<Response>>,
{
accept_with_opts(io, endpoint, Default::default()).await
}
pub async fn accept_with_opts<RW, F, Fut>(
mut io: RW,
endpoint: F,
opts: ServerOptions,
) -> http_types::Result<()>
where
RW: Read + Write + Clone + Send + Sync + Unpin + 'static,
F: Fn(Request) -> Fut,
Fut: Future<Output = http_types::Result<Response>>,
{
loop {
let fut = decode(io.clone());
let req = if let Some(timeout_duration) = opts.headers_timeout {
match timeout(timeout_duration, fut).await {
Ok(Ok(Some(r))) => r,
Ok(Ok(None)) | Err(TimeoutError { .. }) => break,
Ok(Err(e)) => return Err(e),
}
} else {
match fut.await? {
Some(r) => r,
None => break,
}
};
let method = req.method();
let res = endpoint(req).await?;
let mut encoder = Encoder::new(res, method);
io::copy(&mut encoder, &mut io).await?;
}
Ok(())
}