HTTP Adapter
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendix
Introduction
This document is a technical document for Gin-based HTTP adapter, focusing on route registration mechanism, controller layer design pattern, request processing flow and middleware system. The document covers health check, session management and other core route implementations, explains working principles and configuration methods of JWT authentication middleware, authorization middleware, RSA permission verification middleware, and provides best practices for route parameter binding, request validation, response formatting, error handling strategy, performance optimization and security protection, helping Web API developers quickly get started and extend.
Project Structure
HTTP adapter adopts "route layer -> controller layer -> usecase layer" clean architecture layering, combines Gin middleware to implement authentication and authorization. Core directories and responsibilities are as follows:
- Route Layer: Defines HTTP routes and paths, responsible for forwarding requests to controllers
- Controller Layer: Handles request parameters, calls usecase services, wraps responses
- Middleware Layer: Uniformly handles authentication, authorization, signature verification and other cross-cutting concerns
- Configuration and Bootstrap: Application startup, HTTP server configuration, middleware assembly
Core Components
- Route Registrars: Register health check, session management and other routes separately, bind to corresponding controller methods
- Controller Handlers: Wrap business calls and response formatting, handle parameter binding and errors
- Middleware System: JWT authentication, RBAC authorization, RSA client signature verification
- Application Bootstrap: Creates Gin engine, assembles middleware, starts HTTP server
Architecture Overview
The following diagram shows the overall flow from request entering Gin engine to controller processing and usecase service calling, as well as middleware interception positions.
Detailed Component Analysis
Health Check Route and Handler
Route Registration
- Registers /health and /ready two GET routes on root engine
Handler Responsibilities
- Reads application name and version, constructs health/readiness response; supports injection from environment variables or configuration
Response Format
- Unified JSON structure, contains status, message, timestamp and other fields
Session Route and Handler
Route Registration
- Provides session create, query, update, delete and data read and other RESTful routes
Parameter Binding
- Uses Gin's ShouldBindJSON/ShouldBindQuery to bind and validate request body and query parameters
Error Handling
- Returns corresponding status codes for business errors and resource not found scenarios
Response Format
- Uniformly uses JSON return, follows business semantics
Task Route (Reserved)
- Current file is in commented state, reserved task-related route registration and handler definition, convenient for future extension
- Recommend referring to session module's parameter binding and error handling pattern for implementation
Middleware System
JWT Authentication Middleware
- Function: Parses Bearer token from Authorization request header, uses HS256 to validate signature, extracts user claims and writes to context
- Error Classification: Malformed, expired, signature invalid, other invalid, etc., returns different 401 messages separately
- Context Injection: Writes Principal to request context, for subsequent middleware and controller use
RBAC Authorization Middleware
- Function: Performs authorization decision based on username, resource path and HTTP method
- Dependency: Requires JWT middleware to inject username to context first
- Behavior: Returns true/false through Enforce, decides to allow or return 403
RSA Client Signature Middleware
- Function: Validates client request based on RSA-PSS signature, anti-replay, timestamp validation, signature cache and nonce storage
- Configuration: Supports default configuration and configurable configuration, can parse public key from PEM/SSH
- Flow: Read request headers -> Validate timestamp and nonce -> Read request body -> Verify signature -> Cache result -> Allow
Application Bootstrap
Engine Initialization
- Uses gin.Default to create global engine
Middleware Assembly
- Manages middleware collection and named middleware uniformly through Authorization
Server Startup
- Creates http.Server based on configuration, listens port and supports graceful shutdown
Dependency Analysis
- Route Layer Depends on Controller Layer: Route registrars create handler instances through New*Handler factory
- Controller Layer Depends on Usecase Layer: Handlers call SessionService and other usecase services
- Middleware Depends on Authentication Model: JWT middleware depends on UserClaims/Principal; RSA middleware depends on RSAAuthConfig and interface implementations
- Bootstrap Layer Depends on Route and Middleware: App assembles middleware and registers routes during startup
Performance Considerations
- Middleware Order: Place lightweight checks first (such as RSA cache hit), reduces unnecessary decoding and signature computation
- Signature Cache: RSA middleware has built-in signature cache, recommend combining time window and cache key strategy to improve throughput
- Nonce Storage: Uses memory NonceStore for anti-replay, pay attention to race conditions and expiration cleanup under high concurrency
- Request Body Reuse: Need to reset Body after reading request body, avoids subsequent handler unable to read
- Response Format: Uniformly use OK/ERROR/BAD_REQ and other utility functions, reduces repeated serialization overhead
Troubleshooting Guide
Health Check Failed
- Confirm if application name and version in environment variables or configuration are correctly injected
Session Interface Error
- Check if parameter binding passes, if service layer returns business exception, if status code mapping is correct
JWT 401
- Verify Authorization header format, if secret key is consistent, if token is expired or signature invalid
RBAC 403
- Confirm JWT middleware has injected username, if policy rules are correct, if resource path and method match
RSA 401
- Check if request headers are complete, if timestamp is within window, if nonce is duplicate, if signature is valid
Conclusion
This HTTP adapter uses Gin as core, adopts clear layering and middleware system, implements health check, session management and other core capabilities, and provides JWT, RBAC, RSA signature verification three types of middleware to meet diverse security requirements. Through unified response format and error handling strategy, developers can quickly extend new routes and middleware while maintaining good maintainability and security.
Appendix
Route Parameter Binding, Request Validation and Response Formatting Best Practices
Parameter Binding
- Path Parameters: Use c.Param to get
- Query Parameters: Use ShouldBindQuery and mark form tag on struct
- Request Body: Use ShouldBindJSON and mark json and binding tags on struct
Request Validation
- Required Fields: binding:"required"
- Custom Validation: Implement custom validation method on struct
Response Formatting
- Uniformly use OK/DATA/RESULT and other utility functions, ensure code/msg/data structure consistency
- Error Response: Use UNAUTH/BAD_REQ/NOT_FOUND/FAIL and other utility functions
Middleware Extension Guide
JWT Middleware
- Use factory function to pass secret key, returns gin.HandlerFunc
- Add middleware to Authorization and enable on route
RBAC Middleware
- Depends on Casbin Enforcer, ensure username is already in context
- Enable on route group that needs authorization
RSA Middleware
- Provides default configuration and configurable configuration two factory functions
- Supports parsing public key from PEM/SSH, recommend combining signature cache and nonce storage