Middleware System
Middleware System
Core features
Middleware is one of the core features of the SDK framework. It provides a powerful request/response interception mechanism so you can handle cross-cutting concerns uniformly without touching business logic.
Overview
Middleware is a design pattern that lets you insert custom logic into the request lifecycle. The GM Desktop framework middleware system supports:
- Request preprocessing: validation, conversion, logging
- Access control: authentication and authorization checks
- Performance monitoring: timing and profiling
- Response post-processing: formatting, caching, cleanup
Basic Usage
Middleware Interface
Important conventions
- A middleware class must inherit from
RPCMiddleware - It must implement
process_requestandprocess_response - Both methods must return the processed data and must not return
None - Register middleware with
app.middleware()
| Method | Arguments | Returns | Description |
|---|---|---|---|
process_request | request, context | request | Request preprocessing, called before the route handler runs |
process_response | response, context | response | Response post-processing, called after the route handler runs |
Quick Start Example
# main.py - basic middleware example
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc import RPCMiddleware
# Create the app instance
app = ServerApplication("app.socket")
class BasicMiddleware(RPCMiddleware):
"""Basic middleware example"""
def process_request(self, request, context):
"""Request preprocessing - called before business logic"""
print(f"🔍 [request in] {request}")
# Add parameter validation, permission checks, request logging, etc. here
return request # must return the processed request
def process_response(self, response, context):
"""Response post-processing - called after business logic"""
print(f"📤 [response out] {response}")
# Add response formatting, caching, cleanup, etc. here
return response # must return the processed response
# Register middleware (multiple middleware are supported)
app.middleware(BasicMiddleware())
@app.route(name="hello")
async def hello(name: str = "World"):
"""Simple greeting endpoint"""
return jsonify(
data=f"Hello, {name}!",
msg="请求处理成功"
)
if __name__ == "__main__":
asyncio.run(app.run())Best Practices
Design Principles
Middleware design advice
- Single responsibility: each middleware handles exactly one concern.
- Stateless design: avoid storing global state in middleware.
- Error handling: handle possible exceptions properly.
- Performance: avoid slow operations inside middleware.
- Configurability: control middleware behaviour through arguments.
Common Pitfalls
| ❌ Problem | ✅ Solution | 💡 Why |
|---|---|---|
| Forgetting to return data | Make sure both process_request and process_response return a value | Returning None interrupts the request |
| Mutating the original object | Use a deep copy or create a new object | Avoid affecting other middleware |
| Blocking calls | Use async operations or a thread pool | Keep concurrency high |
| Unhandled exceptions | Add try/except blocks | Prevent a middleware crash from taking down the app |
| Order dependencies | Document the dependency clearly | Ensure the correct registration order |
Summary
Middleware is a powerful feature of the GM Desktop framework. Used well, it lets you:
- Decouple business logic: move cross-cutting concerns out of business code
- Improve security: handle authentication and authorization in one place
- Improve observability: centralize logging, metrics and profiling
- Move faster: reuse common functionality and remove duplicated code
Good middleware should be lightweight, focused and reusable.
Common Scenarios
Scenario Overview
| Scenario | Purpose | Where to implement | Example |
|---|---|---|---|
| Logging | Record request and response details | process_request + process_response | Call statistics, error tracing |
| Authentication | Verify identity and permissions | process_request | JWT validation, API key checks |
| Performance monitoring | Measure response time | process_request + process_response | Profiling, slow query monitoring |
| Request transformation | Normalize request format | process_request | Parameter normalization, encoding conversion |
| Response formatting | Normalize response structure | process_response | Data wrapping, error code mapping |
| Cache control | Cache responses | process_request + process_response | Redis cache, in-memory cache |
| Rate limiting | Prevent API abuse | process_request | Frequency limits, IP blocklists |
Real-World Example: Logging Middleware
# main.py
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc import RPCMiddleware
from loguru import logger
class LoggingMiddleware(RPCMiddleware):
def process_request(self, request, context):
logger.info(f"Request data: {request}")
return request
def process_response(self, response, context):
logger.info(f"Response data: {response}")
return response
app = ServerApplication("app.socket")
app.middleware(LoggingMiddleware()) # register the logging middleware
@app.route(name="hello")
async def hello():
return jsonify(data="hello world!", msg="OK")
if __name__ == "__main__":
asyncio.run(app.run())Sample Log Output
2025-05-15 10:42:47.527 | INFO | __main__:process_request:30 - 请求数据:('{"jsonrpc": "2.0", "method": "hello", "id": 1}',)
2025-05-15 10:42:47.528 | INFO | __main__:process_response:34 - 响应数据:{'jsonrpc': '2.0', 'result': {'code': 200, 'meta': {'endpoint': 'OK', 'close': 1}, 'data': 'hello world!', 'msg': 'None'}, 'id': 1}