Interface Adapters
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Component Details
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendix
Introduction
This document focuses on Sparrow's interface adapters, systematically explaining HTTP adapter's routing design, middleware system, request/response processing mechanisms; as well as WebSocket adapter's real-time communication, connection management and message processing flow. Also provides middleware extension methods, custom middleware development guide, middleware chain execution order explanation, and practical recommendations for API version control, request validation, response formatting. Finally gives guidance on performance optimization, error handling strategies and monitoring integration, helping API developers efficiently use and extend adapters.
Project Structure
- HTTP Adapter located under pkg/adapter/http, divided by responsibility:
- router: Route registration layer, responsible for binding specific paths to handlers
- handlers: HTTP handler layer, interfaces with usecase and outputs JSON responses
- middlewares: Middleware layer, provides authentication, authorization, client signature verification and other cross-cutting capabilities
- WebSocket Adapter located in pkg/ws, provides Gin middleware and connection pool, broadcast, single-point/user-level sending, heartbeat and other capabilities
- bootstrap/app.go provides application lifecycle, HTTP server startup and graceful shutdown
- config/app.go defines application configuration structure (name, version, secret key, etc.)
Core Components
- HTTP Route Registration: Centrally register module routes in router package, such as sessions, health checks, etc.
- HTTP Handlers: Implement specific business interfaces in handlers package, bind request parameters, call usecase, output unified JSON
- Middleware System: Provides JWT authentication, RBAC authorization, RSA client signature verification, etc.
- WebSocket Adapter: Provides Gin middleware, connection upgrade, global connection pool, broadcast/single-point/user-level sending, heartbeat keepalive
- Application Bootstrap: bootstrap/app.go responsible for configuration loading, logger initialization, HTTP server startup and graceful shutdown
Architecture Overview
The following diagram shows the position and interaction relationships of HTTP and WebSocket adapters in the application, as well as relationships with bootstrap layer and configuration layer.
Component Details
HTTP Routing and Handlers
Route Registration
- Session Routes: Register session-related paths in router/session.go, bind to handlers.NewSessionHandler
- Health Check Routes: Register /health and /ready in router/health.go, bind to handlers.NewHealthHandler
- Task Routes: Reserved task-related route registration in router/tasks.go (currently commented out, convenient for extension)
Handler Implementation
- Session Handler: Implements create, query, update, delete, get session data and other interfaces, uniformly returns JSON
- Health Check Handler: Outputs health and readiness status, supports reading application name and version from environment variables or configuration
Unified Response
- pkg/http/results.go provides unified error/success/pagination response tools, convenient for standardized output
Middleware System
JWT Authentication Middleware
- Extracts Bearer token from Authorization header, uses HS256 to parse and validate
- Performs detailed processing on v5 version error types (malformed, expired, signature invalid, etc.)
- Writes user principal to context after successful validation, for subsequent handler use
RBAC Authorization Middleware
- Gets username from context (requires preceding JWT middleware)
- Uses Casbin to execute policy matching (resource URI and action HTTP method)
- Returns 403 or allows
RSA Client Signature Middleware
- Reads client ID, signature, nonce, timestamp from request headers
- Validates timestamp window, nonce deduplication, signature verification (RSA-PSS SHA256)
- Supports configurable public key provider, nonce storage, signature cache
- Writes clientID to context after successful validation
WebSocket Adapter
Middleware and Connection Upgrade
- Middleware acts as Gin middleware, recognizes WebSocket handshake and upgrades
- Supports custom CORS validation and heartbeat interval
- Generates clientID, supports reading user_id from query parameters or headers
Connection Management
- Global thread-safe connection pool, indexed by clientID
- Automatic cleanup on disconnect, removes connection on abnormal read
Message Processing and Broadcast
- Broadcast: Send text/JSON/binary messages to all clients
- Single-Point Send: Send by clientID
- User-Level Send: Send by user_id
- Heartbeat Keepalive: Periodically send ping, disconnect on failure
Request Validation and Response Formatting
Request Validation
- Uses Gin's ShouldBindJSON/ShouldBindQuery for structured binding
- Middleware layer can combine JWT/RBAC/RSA for multi-layer validation
Response Formatting
- Uniformly uses pkg/http/results.go's OK/DATA/RESULT and other tools
- Supports standardized output of error codes, messages and data body
API Version Control Practice
- Path Prefix Versioning: Such as /v1/sessions, /v2/tasks
- Header Version: X-API-Version
- Query Parameter Version: ?api-version=v1
- Cooperates with route registration, gradually migrate old interfaces, ensure backward compatibility
[This section is general practice recommendations, no source code reference needed]
Middleware Extension and Custom Development Guide
Adding New Middleware
- Implement gin.HandlerFunc, read request headers, context, request body as needed
- Control chain flow through c.Next()
Middleware Chain Order
- Add in order through r.Use(...) before route registration
- Authentication middleware usually comes first, authorization middleware follows
Testing
- Refer to testing patterns in jwt_test.go and rsa_perm_test.go, construct request headers, request body and expected responses
Dependency Analysis
Performance Considerations
- Middleware Order Optimization: Place expensive middleware (such as signature verification, permission check) after authentication, reduce invalid request processing
- Cache and Deduplication: RSA middleware supports signature cache and nonce storage, reduces duplicate request cost
- Broadcast and Send: WebSocket broadcast uses batch send and failure removal strategy, avoids blocking and accumulation
- Timeout and Concurrency: HTTP server sets reasonable ReadTimeout/WriteTimeout, WebSocket heartbeat period configurable
- Logging and Sampling: Perform log downsampling for high-frequency interfaces, avoid I/O becoming bottleneck
[This section is general performance recommendations, no source code reference needed]
Troubleshooting Guide
JWT Verification Failed
- Check if Authorization header format is Bearer <token>
- Verify secret key and signature algorithm consistency
- Pay attention to v5 version error types (malformed, expired, signature invalid)
RBAC Permission Insufficient
- Confirm username exists in context (JWT middleware has injected)
- Check policy model and permission matrix configuration
RSA Client Signature Failed
- Verify request header fields (client_id, signature, nonce, timestamp)
- Check timestamp window and nonce deduplication
- Confirm public key and private key match and encoding correct
WebSocket Connection Issues
- Check handshake headers Upgrade/Connection
- Pay attention to heartbeat failure and abnormal disconnect logs
- Verify CORS validation and client ID generation logic
Conclusion
Sparrow's interface adapters provide complete HTTP and WebSocket capabilities through clear layering and pluggable middleware system. Through unified route registration, handlers and response tools, developers can quickly build stable and reliable APIs; through JWT, RBAC, RSA and other middleware, meet diverse security requirements; through WebSocket middleware and connection pool, achieve efficient real-time communication. Recommend following middleware chain order, version control and performance optimization strategies in actual projects, continuously improve monitoring and observability.
[This section is summary, no source code reference needed]