Layer: L7 Application ยท Build flags: none (core features only)
What this example teaches
Handlers can queue extra response headers and cookies before they send. The queued headers live in a fixed per-connection buffer, are injected into the next send() / send_empty() / redirect() on that slot, and are cleared automatically at the start of the next request.
The three calls.
server.add_response_header(slot_id, "X-Api-Version", "1.2.5");
server.set_cookie(slot_id, "session", "abc123", "Path=/; HttpOnly; Max-Age=3600");
server.clear_response_headers(slot_id);
The /cleared route queues a header then calls clear_response_headers() before sending, so the header does not appear - useful when a later code path decides the earlier header was wrong. Oversized headers are dropped whole (never truncated mid-line), preserving a valid response.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--lib="." examples/L7-Application/ResponseHeaders/ResponseHeaders.ino
curl -D - http://<ip>/headers # X-Api-Version + Set-Cookie present
curl -D - http://<ip>/cleared # no X-Scratch (cleared before send)
Annotated source
The complete sketch (ResponseHeaders.ino), reproduced verbatim with added explanatory comments:
#include "protocore.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
PC server;
void handle_headers(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.add_response_header(slot_id, "X-Api-Version", "1.2.5");
server.set_cookie(slot_id, "session", "abc123", "Path=/; HttpOnly; Max-Age=3600");
server.send(slot_id, 200, "text/plain", "custom header + cookie attached");
}
void handle_cleared(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.add_response_header(slot_id, "X-Scratch", "should-not-appear");
server.clear_response_headers(slot_id);
server.send(slot_id, 200, "text/plain", "headers were cleared before send");
}
void setup()
{
Serial.begin(115200);
Physical.wifi->init(SSID, PASSWORD);
Serial.print("Connecting to WiFi");
while (!Physical.wifi->ready())
{
delay(250);
Serial.print('.');
}
uint32_t ip = Physical.link->egress_ip();
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
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();
}
@ HTTP_GET
Safe, idempotent read.
Layer 1 (Physical) - link bring-up, the interface registry, and live egress reporting.