routers.go
Overview
This file defines the routing infrastructure for the ADK-Web REST API by declaring HTTP routes and assembling them into a top-level router. It provides abstractions for describing API routes, interfaces for route providers, and utility functions for creating and populating a Gorilla mux router with these routes. This setup is integral to directing incoming HTTP requests to the appropriate handler functions implemented elsewhere in the system, enabling modular and scalable HTTP routing.
The primary purpose is to facilitate the registration and aggregation of multiple API routers (each responsible for a domain of REST endpoints) into a single HTTP router instance used by the web server. It leverages the github.com/gorilla/mux package to support expressive route definitions including HTTP methods, URL patterns, and handler functions.
This routing mechanism is a core component of the broader Router Setup subtopic within the REST API and Web Launchers topic, which organizes REST API endpoints into modular subrouters that connect HTTP requests to controller handlers.
Detailed Explanation of Code Components
Type: Route
type Route struct {
Name string
Methods []string
Pattern string
HandlerFunc http.HandlerFunc
}
Purpose: Represents a single API route's metadata and handling logic.
Fields:
Name(string): A unique identifier for the route, useful for logging, debugging, and route referencing.Methods([]string): A list of allowed HTTP methods (e.g., GET, POST) this route responds to.Pattern(string): The URL path pattern (potentially with variables) that this route matches.HandlerFunc(http.HandlerFunc): The HTTP handler function that processes requests matching this route.
Usage Example:
Route{ Name: "GetUser", Methods: []string{"GET"}, Pattern: "/users/{id}", HandlerFunc: userController.GetUserHandler, }This struct is fundamental for route definition used by all API routers.
Type: Routes
type Routes []Route
Purpose: Defines a slice of
Routestructs, representing a collection of API routes for a router.Usage: Returned by routers implementing the
Routerinterface to enumerate all their routes.
Interface: Router
type Router interface {
Routes() Routes
}
Purpose: Abstracts any API router that can provide a list of its routes.
Function:
Routes() Routes: Returns the complete set of routes handled by that router.
Usage: Enables polymorphic aggregation of multiple routers regardless of their internal structure.
Function: NewRouter
func NewRouter(routers ...Router) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
SetupSubRouters(router)
return router
}
Purpose: Creates and returns a new top-level Gorilla mux router instance configured with routes from any number of subrouters.
Parameters:
routers ...Router: Variadic list of routers implementing theRouterinterface.
Returns: Pointer to a fully configured
*mux.Router.Implementation Details:
Initializes a new Gorilla mux router with
StrictSlash(true), ensuring URL paths with or without trailing slashes are treated equivalently.Calls
SetupSubRoutersto register all provided subrouters’ routes into the mux router.
Note: The current implementation calls
SetupSubRouterswith only the newly created router and no subrouters, meaning this code snippet likely requires the subrouters passed explicitly toSetupSubRoutersin a full implementation.Usage Example:
apiRouter := NewRouter(runtimeRouter, sessionsRouter, artifactsRouter) http.Handle("/api/", apiRouter)
Function: SetupSubRouters
func SetupSubRouters(router *mux.Router, subrouters ...Router) {
for _, api := range subrouters {
for _, route := range api.Routes() {
var handler http.Handler = route.HandlerFunc
router.
Methods(route.Methods...).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
}
}
Purpose: Adds the routes from multiple subrouters into a single
*mux.Routerinstance.Parameters:
router *mux.Router: The mux router to which routes will be added.subrouters ...Router: Variadic list of routers providing routes to add.
Behavior:
Iterates over each provided subrouter.
For each route in the subrouter, registers the route with the mux router by:
Setting allowed HTTP methods.
Setting the URL path pattern.
Naming the route.
Assigning the HTTP handler.
Important Implementation Detail:
The method chaining on
routeris done per route for clean, declarative route registration.The handler is wrapped as an
http.Handler, which currently is directly the route’sHandlerFunc. This could be extended for middleware wrapping.
Usage Context: Called by
NewRouteror other setup routines to compose routes from multiple API domains.
Important Implementation Details and Algorithms
The file uses the
gorilla/muxrouter, which supports advanced routing features such as path variables, method-based routing, and route naming.Routes are defined in a modular fashion via the
Routerinterface, allowing flexible composition of API domains.StrictSlash(true)ensures that requests to/pathand/path/are normalized, avoiding duplicate route handlers.The route registration in
SetupSubRoutersis straightforward without additional middleware or error handling wrappers; these are expected to be applied in the handler functions themselves or in other layers.The file itself does not define any API endpoint handlers but provides the structural glue to integrate various routers, which are implemented elsewhere in the project (e.g., runtime, sessions, artifacts routers).
Interaction with Other Parts of the System
This file is foundational for the REST API and Web Launchers module, specifically the Router Setup subtopic.
It aggregates multiple API routers, each typically tied to a controller handling a domain-specific REST API, such as:
Runtime execution routes (RuntimeAPIRouter)
Session management routes (SessionsAPIRouter)
Artifact handling routes (ArtifactsAPIRouter)
The resulting
*mux.Routeris passed to the HTTP server infrastructure to serve incoming API requests.It relies on the
http.HandlerFuncimplementations provided by controllers, which implement the business logic of the API endpoints.The modular router composition supports extensibility, allowing new API domains to be added by implementing the
Routerinterface and passing them toNewRouter.
Visual Diagram: Router Structure and Workflow
classDiagram
class Route {
+Name: string
+Methods: []string
+Pattern: string
+HandlerFunc: http.HandlerFunc
}
class Routes {
<<slice>>
}
class Router {
+Routes() Routes
}
class mux_Router {
+StrictSlash()
+Methods()
+Path()
+Name()
+Handler()
}
class routers_go {
+NewRouter(routers ...Router) *mux.Router
+SetupSubRouters(router *mux.Router, subrouters ...Router)
}
Router <|.. RuntimeAPIRouter
Router <|.. SessionsAPIRouter
Router <|.. ArtifactsAPIRouter
routers_go --> mux_Router : creates and configures
mux_Router "1" o-- "*" Route : contains
routers_go ..> Router : uses
Route: Represents an individual API route with associated methods, pattern, and handler.Router: Interface for types that provide a collection of routes.mux_Router: The Gorilla mux router that aggregates all routes.routers_go: Contains functions that create and assemble the mux router from multipleRouterimplementations.The diagram shows how different routers implement the
Routerinterface and provide routes that are registered into the mux router.
Summary
The routers.go file provides the core routing abstractions and setup functions for the REST API server by defining Route structures, a Router interface, and methods to create and populate a Gorilla mux router. This supports modular, scalable HTTP routing essential for mapping REST API endpoints to their handlers, linking the HTTP layer to the underlying controller logic described in the REST API and Web Launchers topic and its Router Setup subtopic.