web.go
Overview
The web.go file implements a web server launcher that facilitates running the ADK (Agent Development Kit) via an HTTP web server. This launcher supports modular extensions called sublaunchers, allowing different web-based functionalities (such as REST APIs, web UIs, or custom protocol handlers) to coexist and be configured through command-line flags.
This file provides a framework to:
Parse command-line arguments for the web server and its sublaunchers.
Compose an HTTP router using gorilla/mux.
Register routes from multiple sublaunchers.
Start and manage the lifecycle of the HTTP server with configurable timeouts.
Log HTTP requests and notify users about server status and active sublaunchers.
It acts as the core component of the Web Server Launcher described in the [REST API and Web Launchers](80564) topic, enabling a flexible and extensible web server infrastructure for agent interaction.
Key Entities
webConfig struct
Holds configuration parameters for the web server instance.
Field | Type | Description |
|---|---|---|
|
| TCP port on localhost where the server listens |
Timeout for writing HTTP response | ||
Timeout for reading HTTP request body | ||
Timeout for idle keep-alive connections |
webLauncher struct
The main launcher type that implements the launcher.SubLauncher interface to run the web server.
Field | Type | Description |
|---|---|---|
| Flag set for parsing web server related CLI flags | |
| Web server configuration | |
| List of all available sublaunchers | |
Map of activated sublaunchers keyed by their keyword |
Sublauncher interface
Defines the contract for extensions that add functionality to the web server. Each sublauncher can:
Declare a unique keyword for command-line selection.
Parse its own flags.
Provide CLI usage syntax and descriptions.
Register HTTP routes onto the main router.
Print user messages on web server startup.
type Sublauncher interface {
Keyword() string
Parse(args []string) ([]string, error)
CommandLineSyntax() string
SimpleDescription() string
SetupSubrouters(router *mux.Router, config *launcher.Config) error
UserMessage(webURL string, printer func(v ...any))
}
This interface enables modular web components that integrate seamlessly with the base web server.
Functions and Methods
NewLauncher(sublaunchers ...Sublauncher) launcher.SubLauncher
Creates and returns a new webLauncher instance configured with the provided sublaunchers.
Initializes default web server flags:
-port(default 8080)-write-timeout(default 15s)-read-timeout(default 15s)-idle-timeout(default 60s)
The returned launcher supports parsing these flags and delegates sublaunchers to parse their own flags.
Usage Example:
apiLauncher := api.NewLauncher()
webUILauncher := webui.NewLauncher()
launcher := web.NewLauncher(apiLauncher, webUILauncher)
(*webLauncher) Execute(ctx context.Context, config *launcher.Config, args []string) error
Implements the launcher.Launcher interface.
Parses the command-line
argsusingParse.Enforces that no unrecognized arguments remain.
Invokes
Runto start the web server.
Returns any parsing or runtime errors.
(*webLauncher) Parse(args []string) ([]string, error)
Parses the command-line arguments:
Parses web server flags from
args.Builds a map from sublauncher keywords to sublauncher instances.
Iterates over remaining
argsto detect sublauncher keywords.For each detected keyword:
Ensures uniqueness (no duplicates).
Delegates parsing of that sublauncher's flags.
Marks the sublauncher as active.
Returns any unparsed arguments that do not belong to web launcher or its sublaunchers.
Errors if:
Web server flags fail to parse.
Duplicate sublauncher keywords are specified.
Unknown sublauncher keywords are encountered during parsing.
(*webLauncher) Run(ctx context.Context, config *launcher.Config) error
Starts the HTTP server with active sublaunchers:
Ensures
config.SessionServiceis set (defaults to in-memory session service).Builds the base HTTP router (
BuildBaseRouter).Validates that at least one sublauncher is active.
Invokes
SetupSubrouterson each active sublauncher to register routes.Logs server startup details.
Starts an
http.Serverwith configured timeouts and the composed router.Blocks serving HTTP requests until the server terminates or encounters an error.
Returns any errors encountered during setup or server startup.
(*webLauncher) CommandLineSyntax() string
Builds and returns a formatted string describing:
Web server flags usage.
Available sublaunchers with their keywords and descriptions.
Syntax for each sublauncher.
Useful for displaying help information on the command line.
(*webLauncher) Keyword() string
Returns the fixed keyword "web" used to identify this launcher.
(*webLauncher) SimpleDescription() string
Provides a short description:"starts web server with additional sub-servers specified by sublaunchers"
logger(inner http.Handler) http.Handler
HTTP middleware function that logs each request's method, URI, and processing duration.
Wraps an existing
http.Handler.Records start time before request handling.
Logs details after the handler completes.
Used to enhance observability of HTTP traffic.
BuildBaseRouter() *mux.Router
Creates and returns a new mux.Router configured with:
Strict slash behavior.
The
loggermiddleware applied globally.
This router is the base router onto which sublaunchers register their routes.
Important Implementation Details
Sublauncher Uniqueness:
The launcher enforces unique keywords for sublaunchers to avoid conflicts during parsing.Command-line Parsing Delegation:
The launcher parses its own flags first, then dispatches remaining arguments to sublaunchers by keyword. This design allows modular CLI extension without interference.Middleware Usage:
The singleloggermiddleware logs all incoming HTTP requests, providing request-level timing and method/URI information.HTTP Server Configuration:
The server's read, write, and idle timeouts are configurable via flags, allowing control over request processing and connection lifecycle.Session Service Initialization:
If no session service is provided in the launcher configuration, an in-memory session service is created by default, enabling session management for web interactions.User Messaging:
After server start, each active sublauncher can print custom startup messages, e.g., URLs or instructions for users.
Interaction with Other System Components
The web launcher integrates with the broader
REST API and Web Launcherssystem by acting as the core HTTP server framework.Sublaunchers implement additional web functionalities such as REST API endpoints, web UI serving, or A2A protocol handlers, plugging into this launcher.
The
launcher.Configparameter passed toRuntypically includes configuration for session services, artifact services, and agent loading, linking with topics likeSession ManagementandAgent Execution Runner.The router built by
BuildBaseRouter()is extended by sublaunchers to add their HTTP handlers, following the modular routing design described inRouter Setup.Logging middleware supports observability, complementing tracing and telemetry systems discussed in
Telemetry and Observability.
Visual Diagram: Web Server Launcher Structure and Workflow
flowchart TD
A[Command Line Input] --> B[Parse Web Flags]
B --> C[Identify Sublaunchers]
C --> D[Parse Sublauncher Flags]
D --> E[Build Base Router]
E --> F[Setup Sublaunchers' Routes]
F --> G[Start HTTP Server]
G --> H[Handle HTTP Requests]
H --> I[Log Requests]
classDef launcher fill:#f9f,stroke:#333,stroke-width:1px;
class A,B,C,D,E,F,G,H,I launcher;
Command Line Input: User provides CLI arguments.
Parse Web Flags: Parses flags for web server configuration.
Identify Sublaunchers: Recognizes keywords for each sublauncher.
Parse Sublauncher Flags: Delegates flag parsing to each activated sublauncher.
Build Base Router: Creates base HTTP router with logging middleware.
Setup Sublaunchers' Routes: Each sublauncher registers its HTTP routes.
Start HTTP Server: Starts listening on the specified port.
Handle HTTP Requests: Routes requests to registered handlers.
Log Requests: Logs HTTP method, URI, and duration for each request.
Summary of Core Usage Pattern
Create a
webLauncherviaNewLauncher()with desired sublaunchers.Call
Execute()orParse()followed byRun()to start the web server.The launcher parses flags, activates sublaunchers, builds routes, and runs the HTTP server.
Sublaunchers extend functionality by adding their own CLI flags and HTTP handlers.
Middleware logs requests, and user messages are printed on server startup.
Example Usage Outline
func main() {
apiLauncher := api.NewLauncher()
webUILauncher := webui.NewLauncher()
webL := web.NewLauncher(apiLauncher, webUILauncher)
err := webL.Execute(context.Background(), &launcher.Config{}, os.Args[1:])
if err != nil {
log.Fatalf("Failed to start web server: %v", err)
}
}
This example shows how the web launcher can be composed with REST API and Web UI sublaunchers to provide a full-featured HTTP server.
This documentation describes the design, components, and workflows encapsulated in the web.go file, which implements the foundational Web Server Launcher functionality within the [REST API and Web Launchers](80564) topic.