Handler Layer
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendix
Introduction
This document systematically organizes the design and implementation of HTTP handler layer, focusing on the following aspects:
- Controller layer responsibility separation and position in clean architecture
- Implementation points of health check, session management, task management three types of handlers
- Request parameter validation, business logic invocation, response formatting and error handling flow
- Dependency injection, context management, transaction processing practice details
- JSON response template and status code best practices
- Complete handler development guide and business integration methods for Web developers
Project Structure
Handler layer is located in "interface adapter" layer, responsible for converting HTTP requests to inputs required by domain use cases, then converting use case outputs to standardized HTTP responses. Route layer is responsible for registering endpoints and middleware, handler layer only depends on use case layer and infrastructure configuration.
Core Components
- Health Check Handler: Provides running state and readiness state checks, unified return structure, reads application name and version from environment variables or configuration files.
- Session Handler: Encapsulates session creation, query, update data, delete and get data by key operations; built-in parameter binding and error handling.
- Session Service: Implements session lifecycle management, expiration check and data read/write in use case layer; interacts with repository and logs.
- Entities and Errors: Session entity carries data and expiration time; error module centrally defines session-related errors.
- Route Registration: Binds handler methods to specific paths and HTTP methods.
- Response Template: Unified HTTP response structure, convenient for frontend consumption and status code convention.
- Middleware: JWT authentication and RBAC authorization middleware, performs context injection and permission check throughout request chain.
Architecture Overview
Handler layer follows clean architecture's "interface adapter" responsibility: only handles HTTP details, does not contain business rules; business rules are concentrated in use case layer, entities and repositories are located in core layer.
Detailed Component Analysis
Health Check Handler
Design Points
- Injects configuration object through constructor, reads application name and version from environment variables first, otherwise falls back to configuration.
- Provides running state and readiness state two endpoints, unified return structure includes status, message, timestamp, etc.
Request/Response
- GET /health: Returns running state health information
- GET /ready: Returns readiness state health information
Error Handling
- Current implementation directly returns success status, if external dependency check needed can add database, cache and other connectivity detection in extension.
Best Practices
- Recommend splitting readiness check and liveness check, former for container orchestration, latter for liveness probe.
- Return structure can reuse unified template, convenient for frontend consistent processing.
Session Handler
Design Points
- Injects use case service through dependency injection, handler only responsible for parameter parsing, error handling and response formatting.
- Uses Gin's ShouldBindJSON/ShouldBindQuery for parameter binding and validation.
Main Interfaces
- POST /sessions: Create session
- GET /sessions/:id: Get session
- PUT /sessions/:id/data: Update session data (key-value pairs)
- GET /sessions/:id/data/:key: Get session data by key
- DELETE /sessions/:id: Delete session
Parameter Validation and Error Handling
- Uses struct tags for required field validation; returns 400 on binding failure.
- Returns 404 or 500 according to business exception scenario; returns 200/201 on success.
Response Formatting
- Uniformly uses JSON structure, contains status code, message and data fields.
Context and Transaction
- Handler passes context to use case layer through c.Request.Context(); repository interface suggests executing in transaction to ensure consistency.
Task Handler (Reserved)
Current Status
- File comments out complete task management interface, currently not enabled.
Recommendations
- Adopt same parameter binding, error handling and response template style as session handler.
- Enable corresponding registration function in route layer, and implement corresponding service in use case layer.
Dependency Analysis
Route to Handler
- RegisterHealthRoutes and RegisterSessionRoutes are responsible for registering handler methods to Gin engine.
Handler to Use Case
- SessionHandler depends on SessionService; HealthHandler depends on AppConfig.
Use Case to Entity and Repository
- SessionService depends on repository interface and Session entity, responsible for expiration check and data read/write.
Dependency Injection Container
- Container supports anonymous and named providers, resolves dependencies by type and caches instances, suitable for assembling handlers and services during application startup.
Performance Considerations
Parameter Binding and Validation
- Uses ShouldBindJSON/ShouldBindQuery to reduce repeated parsing and type conversion overhead.
Logging and Errors
- Logs errors in use case layer, avoids heavy IO operations in handler layer.
Response Template
- Unified template reduces memory and CPU overhead caused by serialization differences.
Middleware Order
- Places lightweight middleware (such as parameter binding) at front, heavy middleware (such as authentication, authorization) as needed.
Troubleshooting Guide
Common Errors and Diagnosis
- 400 Parameter Error: Check request body structure and required fields; confirm JSON format is correct.
- 401 Unauthorized: Check Authorization header format and signature; confirm JWT secret key and algorithm match.
- 403 Forbidden: Check RBAC rules and user role mapping.
- 404 Session Not Found: Confirm session ID is correct and not expired; check if use case layer deletes expired sessions.
- 500 Server Error: View use case layer logs and repository exceptions.
Recommendations
- Uniformly use response template functions in handler layer, ensure error fields are consistent.
- Add timeout and retry strategies for critical paths (such as accessing external storage).
Conclusion
Handler layer effectively isolates HTTP details from business logic through clear responsibility division and unified response template. Combined with dependency injection container and middleware mechanism, can achieve high cohesion, low coupling service architecture. Recommend completing task handler and error template unification on existing basis, and enabling task-related endpoints in route layer.
Appendix
JSON Response Template Best Practices
- Success Response: Contains code, msg, data fields; pagination scenarios contain total, page, size.
- Error Response: Contains code, msg; avoid leaking sensitive information.
Status Code Recommendations
- 200: GET/PUT/DELETE success
- 201: POST create success
- 400: Parameter validation failed
- 401: Unauthorized
- 403: Forbidden
- 404: Resource not found
- 500: Internal server error
Transaction Processing Recommendations
- Use transactions in use case layer for operations involving multi-step writes, rollback on failure; propagate transaction context through context in handler layer.