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)

Example Usage:

data := map[string]string{"message": "success"}
EncodeJSONResponse(data, http.StatusOK, w)

errorHandler (Type Alias)

type errorHandler func(http.ResponseWriter, *http.Request) error

NewErrorHandler

func NewErrorHandler(fn errorHandler) http.HandlerFunc

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)

Example Usage:

http.HandleFunc("/future-feature", Unimplemented)

Important Implementation Details


Interactions with Other System Components


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

EncodeJSONResponse

Encodes and writes JSON responses with status codes.

errorHandler

Handler type returning an error for centralized handling.

NewErrorHandler

Wraps handlers to manage and respond to errors uniformly.

Unimplemented

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.