ESP32 WebServer Library – addHandler()

Home / References / ESP32 Library / WebServer Library

Description

The addHandler() method is a powerful function provided by the ESP32 WebServer library that allows you to register custom request handlers for your web server. This method enables you to define specialized behaviors for specific URL patterns or HTTP request types, giving you full control over how your ESP32 web server responds to incoming requests.

Custom handlers are particularly useful when you need to implement complex routing logic, handle specific file types, or process particular API endpoints in your web applications.


Syntax and Usage

The addHandler() method can be used in the following way:

server.addHandler(handler);

Where:

  • Basic Usage: Register a custom handler object that inherits from the RequestHandler class to process specific HTTP requests based on your custom logic.

The method must be called after initializing the WebServer object but before calling begin().


Argument(s)

  • handler: A pointer to a RequestHandler object. This object should be an instance of a class that inherits from the RequestHandler base class and implements the required methods for handling HTTP requests.

Return Value

This method does not return any value (void).


Example Codes

Basic Custom Handler Registration

The following example demonstrates how to create a custom handler that processes requests to a specific endpoint. In this case, we’ll create a handler for API requests that responds with JSON data:

/*
 * Author: Avant Maker
 * Date: March 17, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * addHandler() method to register custom request handlers for your
 * web server.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */
#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password


WebServer server(80);

// Custom authentication handler
class AddedHandler : public RequestHandler {
public:
    AddedHandler(const String& prefix) : _prefix(prefix) {}
    
    bool canHandle(HTTPMethod method, String uri) {
        // Handle all requests that start with the specified prefix
        return uri.startsWith(_prefix);
    }
    
    bool handle(WebServer& server, HTTPMethod requestMethod, String requestUri) {
        Serial.println("AddedHandler");
    }

private:
    String _prefix;
};

void handleRoot() {
    String html = "<html><body>";
    html += "<h1>ESP32 addHandler Example</h1>";
    html += "<p>This is a root area.</p>";
    html += "<p><a href='/addedhandler'>Go to addedhandler Area</a></p>";
    html += "</body></html>";
    
    server.send(200, "text/html", html);
}

void handleAdmin() {
    String html = "<html><body>";
    html += "<h1>AddedHandler Area</h1>";
    html += "<p>This is a AddedHandler area.</p>";
    html += "<p><a href='/'>Go to Root Area</a></p>";
    html += "</body></html>";
    
    server.send(200, "text/html", html);
}

void setup() {
    Serial.begin(115200);
    
    // Connect to WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    Serial.print("Connected to WiFi. IP Address: ");
    Serial.println(WiFi.localIP());
    
    // Add handler for the root area
    server.addHandler(new AddedHandler("/addedhandler"));
    
    // Regular route handlers
    server.on("/", HTTP_GET, handleRoot);
    server.on("/addedhandler", HTTP_GET, handleAdmin);
    
    // Start the server
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}
error: Content is protected !!