| 2 |
raymond |
1 |
// SPDX-License-Identifier: LGPL-3.0-or-later
|
|
|
2 |
// Copyright 2016-2026 Hristo Gochkov, Mathieu Carbou, Emil Muratov, Will Miles
|
|
|
3 |
|
|
|
4 |
//
|
|
|
5 |
// Show how to rate limit the server or some endpoints
|
|
|
6 |
//
|
|
|
7 |
|
|
|
8 |
#include <Arduino.h>
|
|
|
9 |
#if defined(ESP32) || defined(LIBRETINY)
|
|
|
10 |
#include <AsyncTCP.h>
|
|
|
11 |
#include <WiFi.h>
|
|
|
12 |
#elif defined(ESP8266)
|
|
|
13 |
#include <ESP8266WiFi.h>
|
|
|
14 |
#include <ESPAsyncTCP.h>
|
|
|
15 |
#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
|
|
|
16 |
#include <RPAsyncTCP.h>
|
|
|
17 |
#include <WiFi.h>
|
|
|
18 |
#endif
|
|
|
19 |
|
|
|
20 |
#include <ESPAsyncWebServer.h>
|
|
|
21 |
|
|
|
22 |
static AsyncWebServer server(80);
|
|
|
23 |
static AsyncRateLimitMiddleware rateLimit;
|
|
|
24 |
|
|
|
25 |
void setup() {
|
|
|
26 |
Serial.begin(115200);
|
|
|
27 |
|
|
|
28 |
#if ASYNCWEBSERVER_WIFI_SUPPORTED
|
|
|
29 |
WiFi.mode(WIFI_AP);
|
|
|
30 |
WiFi.softAP("esp-captive");
|
|
|
31 |
#endif
|
|
|
32 |
|
|
|
33 |
// maximum 5 requests per 10 seconds
|
|
|
34 |
rateLimit.setMaxRequests(5);
|
|
|
35 |
rateLimit.setWindowSize(10);
|
|
|
36 |
|
|
|
37 |
// run quickly several times:
|
|
|
38 |
//
|
|
|
39 |
// curl -v http://192.168.4.1/
|
|
|
40 |
//
|
|
|
41 |
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
|
|
42 |
request->send(200, "text/plain", "Hello, world!");
|
|
|
43 |
});
|
|
|
44 |
|
|
|
45 |
// run quickly several times:
|
|
|
46 |
//
|
|
|
47 |
// curl -v http://192.168.4.1/rate-limited
|
|
|
48 |
//
|
|
|
49 |
server
|
|
|
50 |
.on(
|
|
|
51 |
"/rate-limited", HTTP_GET,
|
|
|
52 |
[](AsyncWebServerRequest *request) {
|
|
|
53 |
request->send(200, "text/plain", "Hello, world!");
|
|
|
54 |
}
|
|
|
55 |
)
|
|
|
56 |
.addMiddleware(&rateLimit); // only rate limit this endpoint, but could be applied globally to the server
|
|
|
57 |
|
|
|
58 |
server.begin();
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
// not needed
|
|
|
62 |
void loop() {
|
|
|
63 |
delay(100);
|
|
|
64 |
}
|