Layer: L7 Application ยท Build flags: none (core features only)
What this example teaches
use() registers a middleware that runs - in registration order - before every request reaches its route handler. Each middleware returns MW_NEXT to fall through or MW_HALT to short-circuit (after sending its own response). A built-in fixed-window rate limiter runs ahead of the chain. This shows logging, header stamping, a hard gate, and the limiter together.
The chain. Three middlewares: one logs every request (even unmatched ones), one stamps a response header, one blocks /admin outright:
Serial.printf(
"[req %lu] %s %s\n", ++request_count, req->
method, req->
path);
}
if (strcmp(req->
path,
"/admin") == 0) {
server.send(slot_id, 403, "text/plain", "blocked by middleware");
}
}
...
server.use(mw_log);
server.use(mw_brand);
server.use(mw_block_admin);
MwResult
Outcome of a middleware function (see Middleware).
@ MW_HALT
Stop dispatch; the middleware already sent a response.
@ MW_NEXT
Continue to the next middleware / the route handler.
Fully-parsed HTTP/1.1 request.
char path[MAX_PATH_LEN]
URL path, null-terminated; no query string.
char method[PC_METHOD_BUF_SIZE]
HTTP method, null-terminated (OPTIONS, or WebDAV methods when enabled).
A middleware can queue response headers with add_response_header() (as mw_brand does with X-Powered-By), so cross-cutting concerns live in one place instead of in every handler.
The rate limiter. enable_rate_limit(max, window_ms) installs a fixed-window limiter ahead of the chain; once more than max requests arrive within the window, further requests get 429 + Retry-After automatically:
server.enable_rate_limit(5, 10000);
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--lib="." examples/L7-Application/Middleware/Middleware.ino
curl -D - http://<ip>/ # see X-Powered-By stamped by middleware
for i in $(seq 1 8); do curl -s -o /dev/null -w "%{http_code} " http://<ip>/ping; done; echo # some 429s
curl http://<ip>/admin # 403 from the gate middleware
Annotated source
The complete sketch (Middleware.ino), reproduced verbatim with added explanatory comments:
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
static unsigned long request_count = 0;
{
(void)slot_id;
request_count++;
Serial.printf(
"[req %lu] %s %s\n", request_count, req->
method, req->
path);
}
{
(void)req;
}
{
if (strcmp(req->
path,
"/admin") == 0)
{
server.
send(slot_id, 403,
"text/plain",
"blocked by middleware");
}
}
void handle_root(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.
send(slot_id, 200,
"text/plain",
"hello from the handler");
}
void handle_ping(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.
send(slot_id, 200,
"text/plain",
"pong");
}
void handle_admin(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.
send(slot_id, 200,
"text/plain",
"you should never see this");
}
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to WiFi");
{
delay(250);
Serial.print('.');
}
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
server.
use(mw_block_admin);
int32_t result = server.
begin(80);
if (result < 0)
{
Serial.printf("begin() failed (error %d)\n", result);
return;
}
Serial.println("Server started on port 80");
}
void loop()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
void enable_rate_limit(uint16_t max_requests, uint32_t window_ms)
Enable a built-in fixed-window request rate limiter.
void use(Middleware mw)
Register a middleware to run before every request is dispatched.
void add_response_header(uint8_t slot_id, const char *name, const char *value)
Queue a custom response header for the next send on this slot.
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_GET
Safe, idempotent read.