forked from ivmarkov/edge-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_server.rs
68 lines (51 loc) · 1.6 KB
/
http_server.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
use core::fmt::{Debug, Display};
use edge_http::io::server::{Connection, DefaultServer, Handler};
use edge_http::io::Error;
use edge_http::Method;
use edge_nal::TcpBind;
use embedded_io_async::{Read, Write};
use log::info;
fn main() {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);
let mut server = DefaultServer::new();
futures_lite::future::block_on(run(&mut server)).unwrap();
}
pub async fn run(server: &mut DefaultServer) -> Result<(), anyhow::Error> {
let addr = "0.0.0.0:8881";
info!("Running HTTP server on {addr}");
let acceptor = edge_nal_std::Stack::new()
.bind(addr.parse().unwrap())
.await?;
server.run(None, acceptor, HttpHandler).await?;
Ok(())
}
struct HttpHandler;
impl Handler for HttpHandler {
type Error<E>
= Error<E>
where
E: Debug;
async fn handle<T, const N: usize>(
&self,
_task_id: impl Display + Copy,
conn: &mut Connection<'_, T, N>,
) -> Result<(), Self::Error<T::Error>>
where
T: Read + Write,
{
let headers = conn.headers()?;
if headers.method != Method::Get {
conn.initiate_response(405, Some("Method Not Allowed"), &[])
.await?;
} else if headers.path != "/" {
conn.initiate_response(404, Some("Not Found"), &[]).await?;
} else {
conn.initiate_response(200, Some("OK"), &[("Content-Type", "text/plain")])
.await?;
conn.write_all(b"Hello world!").await?;
}
Ok(())
}
}