Class RouterConfig
The RouterConfig class serves as the central routing mechanism for the HTTP server,
mapping URL path patterns to their corresponding RequestHandler implementations.
It provides intelligent pattern matching, including support for wildcard patterns and
parameterized routes, with fallback to a default static file handler when no route matches.
Key features:
- Dynamic route registration for custom handlers
- Pattern matching with wildcard support (e.g., /api/*, /users/:id)
- Exact path matching with O(1) lookup performance
- Fallback to default handler for unmatched routes (typically static file serving)
- SSE handler discovery for Server-Sent Events support
Route matching strategy (in order of precedence):
- Exact path match - Direct O(1) map lookup
- Pattern match - Iterates through registered patterns
- Default handler - Static file serving from configured document root
Supported pattern formats:
- Exact paths:
/api/users- Matches only this exact path - Wildcard suffix:
/api/todos/*- Matches /api/todos and all subpaths - Regex patterns:
/users/[0-9]+- Custom regex patterns
Usage example:
RouterConfig router = new RouterConfig("/var/www/html");
router.register("/api/users", new UserHandler());
router.register("/api/todos/*", new TodoHandler());
router.register("/events", new SSEHandler());
// During request handling
RequestHandler handler = router.findHandler(request);
HTTPResponse response = handler.handle(request);
Thread-safety: This class is not thread-safe. Routes should be registered during initialization before concurrent request handling begins. The findHandler method can be called concurrently once initialization is complete.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionRouterConfig(String staticPath) Constructs a RouterConfig instance with a default static file handler. -
Method Summary
Modifier and TypeMethodDescriptionfindHandler(HTTPRequest request) Finds the appropriate request handler for the given HTTP request.Retrieves the first registered SSE handler from the routes.voidregister(String pathPattern, RequestHandler handler) Registers a new route with its corresponding request handler.
-
Constructor Details
-
RouterConfig
Constructs a RouterConfig instance with a default static file handler.The static file handler is configured with the specified root path and will serve files from this location when no matching route is found. This allows the router to handle both dynamic routes (registered handlers) and static content (files from the file system).
The static path should point to a directory containing the static assets to be served (HTML, CSS, JavaScript, images, etc.). This is typically set to the document root of the virtual host.
- Parameters:
staticPath- The root directory path for serving static files. Should be an absolute or relative path to a valid directory. Must not be null.
-
-
Method Details
-
register
Registers a new route with its corresponding request handler.This method maps a URL path pattern to a handler implementation. When an incoming request matches the pattern, the associated handler will be invoked to process the request. Multiple handlers can be registered for different patterns.
Path pattern formats:
- Exact paths: "/api/users" - Matches only this exact path
- Wildcard suffix: "/api/todos/*" - Matches the prefix and all subpaths
- Regex patterns: Any pattern containing wildcards will be treated as regex
If a pattern is registered multiple times, the last registration will overwrite previous ones. Routes should typically be registered during application startup before request handling begins.
Examples:
router.register("/api/users", userHandler); // Exact match router.register("/api/todos/*", todoHandler); // Wildcard suffix router.register("/files/[a-z]+\\.txt", fileHandler); // Regex pattern- Parameters:
pathPattern- The URL path pattern for the route. Can be an exact path, wildcard pattern, or regex pattern. Must not be null.handler- The request handler that will process requests matching this pattern. Must not be null.
-
findHandler
Finds the appropriate request handler for the given HTTP request.This method implements a three-tier matching strategy to find the best handler for the request:
- Exact match: Checks if the request path exactly matches a registered route (O(1))
- Pattern match: Iterates through patterns to find a matching wildcard or regex route
- Default handler: Returns the static file handler if no route matches
The matching algorithm prioritizes exact matches for performance, then falls back to pattern matching which may involve regex evaluation. This ensures common paths (like API endpoints) are resolved quickly while still supporting flexible routing.
Pattern matching supports:
- Wildcard suffix patterns: "/api/todos/*" matches "/api/todos" and "/api/todos/123"
- Regex patterns: Any pattern with wildcards is converted to regex
If no route matches, the default handler (typically
StaticFileHandler) is returned, which will attempt to serve the requested path as a static file from the document root. This provides seamless integration of dynamic and static content.- Parameters:
request- The HTTP request for which to find a handler. Contains the request path used for matching. Must not be null.- Returns:
- The matching request handler if a route matches, or the default handler (static file handler) if no route matches. Never returns null.
-
getSSEHandler
Retrieves the first registered SSE handler from the routes.This method searches through all registered handlers to find an instance of
SSEHandler. SSE handlers provide Server-Sent Events functionality for real-time, unidirectional server-to-client communication.This method is useful for:
- Initializing the
ServerLoggerwith SSE support - Broadcasting server events to all connected SSE clients
- Checking if SSE functionality is available in the current configuration
Note: If multiple SSE handlers are registered, only the first one encountered during iteration will be returned. The order is not guaranteed due to HashMap iteration behavior. Typically, only one SSE handler should be registered per router configuration.
- Returns:
- The first
SSEHandlerfound in the registered routes, ornullif no SSE handler is registered.
- Initializing the
-