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:**

**Return Value:** None.

**Behavior:**

**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:**

**Return Value:** None.

**Behavior:**

**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:**

**Return Value:** None.

**Behavior:**

**Usage Example:**

http.HandleFunc("/documentation", DocsRedirect)

Implementation Details


Interaction with Other Parts of the System


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.