handlers.go
Overview
The handlers.go file in the controllers package implements essential HTTP handler utilities for the ADK-Web REST API. Its primary purpose is to provide reusable functions and types to facilitate JSON response encoding and standardized error handling in HTTP endpoints. This file defines mechanisms to marshal response data into JSON format, send appropriate HTTP status codes, and handle errors returned from HTTP handlers in a uniform manner.
The utilities here serve as foundational building blocks for REST API controllers by abstracting common response and error writing logic, allowing higher-level handlers to focus on business logic. Interaction with HTTP requests and responses is done via the standard net/http package.
This file is closely related to the REST API handler implementations referenced in the broader [REST API and Web Launchers](80564) topic, where HTTP routing and handler registration occur.
Functions and Types
EncodeJSONResponse
func EncodeJSONResponse(i any, status int, w http.ResponseWriter)
Purpose: Marshals a Go interface to JSON and writes it to an HTTP response, setting the appropriate
Content-Typeheader and HTTP status code.Parameters:
i any: The data to encode and send in the response body. Ifnil, no body is written.status int: The HTTP status code to set on the response.w http.ResponseWriter: The response writer to write headers and body.
Return Value: None.
Usage:
Used to send structured JSON responses from REST API handlers.
Automatically sets
Content-Typetoapplication/json; charset=UTF-8.Writes the status code before encoding.
Handles encoding errors by writing an HTTP 500 error.
Example Usage:
data := map[string]string{"message": "success"}
EncodeJSONResponse(data, http.StatusOK, w)
errorHandler (Type Alias)
type errorHandler func(http.ResponseWriter, *http.Request) error
Description: Defines a function signature for HTTP handlers that return an error. This enables the use of a wrapper to centralize error handling logic.
Parameters:
http.ResponseWriter: Response writer for writing HTTP responses.*http.Request: Incoming HTTP request.
Returns:
error: An error that occurred during processing, ornilif none.
NewErrorHandler
func NewErrorHandler(fn errorHandler) http.HandlerFunc
Purpose: Wraps an
errorHandlerfunction to produce a standardhttp.HandlerFuncwhich handles errors returned by the wrapped handler.Parameters:
fn errorHandler: The handler function that may return an error.
Returns:
http.HandlerFunc: A standard HTTP handler that writes error responses iffnreturns an error.
Behavior:
Calls the wrapped handler function
fn.If an error is returned:
If the error implements
statusError(an interface withStatus()), the response writes the error message and the specific status code.Otherwise, writes an HTTP 500 Internal Server Error.
Usage:
Simplifies error handling in HTTP handlers by centralizing error response logic.
Ensures consistent HTTP error responses throughout the API.
Example Usage:
func myHandler(w http.ResponseWriter, r *http.Request) error {
// handler logic
return nil // or error
}
http.HandleFunc("/endpoint", NewErrorHandler(myHandler))
Unimplemented
func Unimplemented(rw http.ResponseWriter, req *http.Request)
Purpose: Sends a
501 Not ImplementedHTTP response.Parameters:
rw http.ResponseWriter: Response writer.req *http.Request: Incoming HTTP request.
Returns: None.
Usage:
Used as a placeholder for endpoints that are not yet implemented.
Clients receive a clear indication that the API feature is unavailable.
Example Usage:
http.HandleFunc("/future-feature", Unimplemented)
Important Implementation Details
The function
EncodeJSONResponsesets theContent-Typeheader to"application/json; charset=UTF-8"to ensure clients interpret the response as UTF-8 encoded JSON.Error handling in
EncodeJSONResponseis defensive: if JSON encoding fails, it writes an HTTP 500 response to avoid silent failures.The
NewErrorHandlerfunction accepts handlers that return errors, enabling a clean separation of error handling logic from business logic in HTTP handlers.The
statusErrorinterface checked inNewErrorHandleris expected to be implemented by errors carrying an HTTP status code, allowing customized error responses. Although not defined in this file, it is implied to exist elsewhere in the system.The
Unimplementedhandler is a simple utility that immediately returns a 501 status without any body content.
Interactions with Other System Components
This file is part of the
REST API and Web Launcherstopic as it provides core HTTP controller utilities for API handlers.Handlers defined here are designed to be used by REST API endpoint implementations responsible for managing resources such as runtime sessions, artifacts, and debug APIs.
The error handling approach facilitates integration with the broader error and status management conventions used throughout the API controllers.
Although marked with a TODO comment, these utilities are currently part of the public
controllerspackage but are intended for internal use, indicating planned refactoring to encapsulate these helpers further.This file relies on standard Go libraries:
encoding/jsonfor serialization, andnet/httpfor HTTP protocol handling.
Diagram: Function Interaction Flow
flowchart TD
A[HTTP Request] --> B["Handler Function<br/>(errorHandler)"]
B -->|returns error| C[NewErrorHandler Wrapper]
C --> D{Error?}
D -- Yes --> E{Implements statusError?}
E -- Yes --> F[Write error message and status code]
E -- No --> G[Write 500 Internal Server Error]
D -- No --> H[Write HTTP Response normally<br/>via EncodeJSONResponse]
H --> I[HTTP Response]
This flowchart illustrates the execution and error handling flow for HTTP handlers wrapped by NewErrorHandler. It shows how an incoming request is processed, errors are checked, and appropriate HTTP responses are written.
Summary of Key Elements
Element | Description |
|---|---|
| Encodes and writes JSON responses with status codes. |
| Handler type returning an error for centralized handling. |
| Wraps handlers to manage and respond to errors uniformly. |
| Simple handler returning HTTP 501 Not Implemented. |
This handlers.go file is a foundational utility module for the REST API controllers, enabling consistent JSON response encoding and error response handling, thereby supporting the robustness and maintainability of the API server.