handlers.go
Overview
The [handlers.go](/projects/291/69247) file is a utility module within the [api](/projects/291/69281) package that provides HTTP response and error handling functions for the API server. It focuses on standardizing JSON responses for both successful and error cases and includes a simple HTTP redirect handler for documentation access.
This file centralizes response formatting logic to ensure consistent HTTP headers and JSON structures are used across the API, improving maintainability and reducing repetitive code in request handlers.
Functions
HandleResponse
func HandleResponse(w http.ResponseWriter, status int, res interface{})
**Purpose:** Sends a JSON-encoded HTTP response with a given status code and response body.
**Parameters:**
w http.ResponseWriter
The HTTP response writer used to send the response back to the client.status int
The HTTP status code to set in the response (e.g., 200 for OK, 201 for Created).res interface{}
The data structure or value to be JSON-encoded and sent in the response body.
**Return Value:** None.
**Behavior:**
Sets the
Content-Typeheader toapplication/json.Writes the provided HTTP status code.
Encodes the
resparameter as JSON and writes it to the response.Logs an error if JSON encoding fails but does not modify the response after writing headers.
**Usage Example:**
responseData := map[string]string{"message": "success"}
HandleResponse(w, http.StatusOK, responseData)
HandleError
func HandleError(w http.ResponseWriter, status int, message string)
**Purpose:** Sends a JSON-encoded error response with a specific HTTP status code and error message.
**Parameters:**
w http.ResponseWriter
The HTTP response writer.status int
The HTTP status code representing the error type (e.g., 400 Bad Request, 500 Internal Server Error).message string
A human-readable error message to include in the response.
**Return Value:** None.
**Behavior:**
Sets the
Content-Typeheader toapplication/json.Writes the provided HTTP status code.
Constructs an error object based on the status code:
For 400 (Bad Request), uses
BadRequestError{Error: message}For 500 (Internal Server Error), uses
InternalServerError{Message: message}For other status codes, uses a generic
Error{Message: message}
Encodes the error object as JSON and writes it to the response.
Logs encoding errors if they occur.
**Note:** The types `BadRequestError`, `InternalServerError`, and `Error` are assumed to be defined elsewhere in the project, encapsulating error message structures.
**Usage Example:**
HandleError(w, http.StatusBadRequest, "invalid request payload")
DocsRedirect
func DocsRedirect(w http.ResponseWriter, r *http.Request)
**Purpose:** Redirects incoming HTTP requests to the API documentation endpoint.
**Parameters:**
w http.ResponseWriter
The HTTP response writer.r *http.Request
The incoming HTTP request.
**Return Value:** None.
**Behavior:**
Issues an HTTP 302 (Found) redirect to the path
/docs/.Useful for redirecting root or legacy documentation routes to the current documentation landing page.
**Usage Example:**
http.HandleFunc("/documentation", DocsRedirect)
Implementation Details
Logging:
The file uses a logger instance created bylog.WithoutFields()from the internallogpackage for error logging during JSON encoding failures.JSON Encoding:
The standard Goencoding/jsonpackage is used for encoding response data and error messages to JSON format.HTTP Headers:
All responses set theContent-Typeheader explicitly toapplication/jsonto ensure clients interpret the response correctly.Error Handling Strategy:
The error response function distinguishes error types by HTTP status code to provide more meaningful error payloads, suggesting there is a structured error model in the broader application.
Interaction with Other Parts of the System
This file depends on the internal
logpackage for logging errors.Relies on error types (
BadRequestError,InternalServerError,Error) defined elsewhere in the codebase, indicating a shared error model.It is designed to be called by various HTTP handlers throughout the API server to send consistent responses.
The redirect handler facilitates navigation within the API service, linking to documentation resources.
Mermaid Diagram
flowchart TD
A[HandleResponse] -->|Encodes JSON response| B[http.ResponseWriter]
C[HandleError] -->|Selects error struct based on status| D{Status Code}
D -->|400| E[BadRequestError]
D -->|500| F[InternalServerError]
D -->|Other| G[Error]
C -->|Encodes JSON error| B
H[DocsRedirect] -->|Issues HTTP 302 redirect| I[/docs/ URL]
subgraph Logging
J[logger.Errorf]
end
A --> J
C --> J
Summary
The [handlers.go](/projects/291/69247) file provides concise helper functions to standardize HTTP JSON responses and error handling in the API. It ensures uniform content types, status codes, and JSON formats for successful and error responses, while also providing a simple redirect handler for API documentation. This modular approach enhances maintainability and consistency across the API service.