SendNakedHttp.ino 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #if defined(ARDUINO_ARCH_ESP8266)
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266WebServer.h>
  4. #elif defined(ARDUINO_ARCH_ESP32)
  5. #include <WiFi.h>
  6. #include <WebServer.h>
  7. #endif
  8. #include <PageBuilder.h>
  9. // Modify according to your Wi-Fi environment.
  10. #define SSID "wifissid"
  11. #define PSK "wifipassword"
  12. // This example shows the utility to send http response
  13. // independently in the token function.
  14. // If the sketch sends independently http response within
  15. // the token function then it must inform to the PageBuilder
  16. // about sending stop for http:200.
  17. #if defined(ARDUINO_ARCH_ESP8266)
  18. ESP8266WebServer server;
  19. #elif defined(ARDUINO_ARCH_ESP32)
  20. WebServer server;
  21. #endif
  22. String tokenFunc(PageArgument&);
  23. PageElement elm("{{RES}}", {{ "RES", tokenFunc }});
  24. PageBuilder page("/", { elm }); // Accessing "/" will call the tokenFunc.
  25. PageElement elmHello("hello, world");
  26. PageBuilder pageHello("/hello", { elmHello });
  27. // The tokenFunc returns no HTML and sends redirection-code as
  28. // particular response by an owned http header.
  29. String tokenFunc(PageArgument& args) {
  30. // When accessing "/", it sends its own http response so that
  31. // it will be transferred to "/hello".
  32. server.sendHeader("Location", "/hello", true);
  33. server.sendHeader("Connection", "keep-alive");
  34. server.send(302, "text/plain", "");
  35. server.client().stop();
  36. // The cancel method notifies sending stop to the PageBuilder.
  37. page.cancel();
  38. return "";
  39. }
  40. void setup() {
  41. delay(1000);
  42. Serial.begin(115200);
  43. Serial.println();
  44. WiFi.mode(WIFI_STA);
  45. WiFi.begin(SSID, PSK);
  46. while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  47. delay(300);
  48. }
  49. page.insert(server);
  50. pageHello.insert(server);
  51. server.begin();
  52. Serial.println("http server:" + WiFi.localIP().toString());
  53. }
  54. void loop() {
  55. server.handleClient();
  56. }