ProtoCore v0.0.1
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
Middleware - a composable request pipeline

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:

static MwResult mw_log(uint8_t slot_id, HttpReq *req) {
Serial.printf("[req %lu] %s %s\n", ++request_count, req->method, req->path);
return MwResult::MW_NEXT; // fall through
}
static MwResult mw_block_admin(uint8_t slot_id, HttpReq *req) {
if (strcmp(req->path, "/admin") == 0) {
server.send(slot_id, 403, "text/plain", "blocked by middleware");
return MwResult::MW_HALT; // the route handler is never reached
}
}
...
server.use(mw_log);
server.use(mw_brand);
server.use(mw_block_admin);
MwResult
Outcome of a middleware function (see Middleware).
Definition protocore.h:138
@ 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); // 5 requests / 10 s

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:

// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-or-later
#include "protocore.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
PC server;
static unsigned long request_count = 0;
// Logging middleware: observe every request (even unmatched 404s), fall through.
static MwResult mw_log(uint8_t slot_id, HttpReq *req)
{
(void)slot_id;
request_count++;
Serial.printf("[req %lu] %s %s\n", request_count, req->method, req->path);
}
// Header-stamp middleware: queue a header onto every response.
static MwResult mw_brand(uint8_t slot_id, HttpReq *req)
{
(void)req;
server.add_response_header(slot_id, "X-Powered-By", "ProtoCore");
}
// Gate middleware: block a path outright, demonstrating MW_HALT.
static MwResult mw_block_admin(uint8_t slot_id, HttpReq *req)
{
if (strcmp(req->path, "/admin") == 0)
{
server.send(slot_id, 403, "text/plain", "blocked by middleware");
return MwResult::MW_HALT; // handler is never reached
}
}
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");
}
// Registered, but the gate middleware blocks it before we get here.
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);
init_wifi_physical(SSID, PASSWORD);
Serial.print("Connecting to WiFi");
while (!wifi_ready())
{
delay(250);
Serial.print('.');
}
uint32_t ip = pc_net_egress_ip(); // library egress IP (network byte order), no Arduino WiFi
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_log); // runs in registration order...
server.use(mw_brand);
server.use(mw_block_admin);
server.enable_rate_limit(5, 10000); // ...behind a 5-req / 10-s limiter
server.on("/", HttpMethod::HTTP_GET, handle_root);
server.on("/ping", HttpMethod::HTTP_GET, handle_ping);
server.on("/admin", HttpMethod::HTTP_GET, handle_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()
{
server.handle();
}
Single-port HTTP server with deterministic, zero-allocation execution.
Definition protocore.h:348
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.
Definition response.cpp:336
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.
Definition physical.cpp:41
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
Definition physical.cpp:77
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Definition physical.cpp:45
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_GET
Safe, idempotent read.