Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Aug 1, 2024. It is now read-only.

Commit de8ada5

Browse files
committed
Middleware demo
1 parent 4fb7914 commit de8ada5

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

src/main.rs

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,8 +1181,38 @@ fn httpd_ulp_endpoints(
11811181
fn httpd(
11821182
mutex: Arc<(Mutex<Option<u32>>, Condvar)>,
11831183
) -> Result<esp_idf_svc::http::server::EspHttpServer> {
1184-
use embedded_svc::http::server::{Method, Request, Response};
1184+
use embedded_svc::http::server::{
1185+
handler, Connection, FnHandler, Handler, HandlerResult, Method, Middleware, Request,
1186+
Response,
1187+
};
11851188
use embedded_svc::io::Write;
1189+
use esp_idf_svc::http::server::EspHttpConnection;
1190+
1191+
struct SampleMiddleware {}
1192+
1193+
impl<C> Middleware<C> for SampleMiddleware
1194+
where
1195+
C: Connection,
1196+
{
1197+
fn handle<'a, H>(&'a self, connection: C, handler: &'a H) -> HandlerResult
1198+
where
1199+
H: Handler<C>,
1200+
{
1201+
info!("Middleware called");
1202+
1203+
handler.handle(connection)
1204+
}
1205+
}
1206+
1207+
// Necessary, until I figure out a more decent solution that does not
1208+
// refer to `EspHttpConnection`, but to the Connection trait instead
1209+
// (if at all possible)
1210+
fn fix_hrtb<F>(f: F) -> F
1211+
where
1212+
F: for<'a, 'b> Fn(Request<&'a mut EspHttpConnection<'b>>) -> HandlerResult,
1213+
{
1214+
f
1215+
}
11861216

11871217
let mut server = esp_idf_svc::http::server::EspHttpServer::new(&Default::default())?;
11881218

@@ -1202,9 +1232,19 @@ fn httpd(
12021232

12031233
Ok(())
12041234
})?
1205-
.fn_handler("/panic", Method::Get, |_req| {
1235+
.fn_handler("/panic", Method::Get, |req| {
12061236
panic!("User requested a panic!")
1207-
})?;
1237+
})?
1238+
.handler(
1239+
"/middleware",
1240+
Method::Get,
1241+
SampleMiddleware {}.compose(handler(fix_hrtb(|req| {
1242+
req.into_ok_response()?
1243+
.write_all("Middleware handler called".as_bytes())?;
1244+
1245+
Ok(())
1246+
}))),
1247+
)?;
12081248

12091249
#[cfg(esp32s2)]
12101250
httpd_ulp_endpoints(&mut server, mutex)?;

0 commit comments

Comments
 (0)