Closed devuri closed 3 weeks ago
In a production environment, health checks are crucial for monitoring the status of essential services, such as database connections or external APIs. This example demonstrates a simple health check middleware that can be easily extended to include more comprehensive checks for various system components.
Here’s how we can implement the Health Check Middleware:
<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Nyholm\Psr7\Response;
class HealthCheckMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Check if the request path is `/health`
if ($request->getUri()->getPath() === '/health') {
// Perform any health checks you need (e.g., database, cache, etc.)
// For now, we'll return a basic success response
$status = [
'status' => 'OK',
'timestamp' => (new \DateTime())->format(\DateTime::RFC3339),
];
// Return a 200 OK response with a JSON payload
return new Response(200, ['Content-Type' => 'application/json'], json_encode($status));
}
// If the route is not `/health`, delegate to the next handler
return $handler->handle($request);
}
}
This method checks if the request path is /health
. If the path matches, it returns a JSON response with status OK
and a timestamp. Otherwise, it passes the request to the next middleware or final handler.
200 OK Response
: A typical health check response will include a 200 OK
status with a JSON payload to indicate the system’s health.
json_encode($status)
: The health status is returned as a JSON string.
Now, integrate this HealthCheckMiddleware
into the middleware stack. If we navigate to /health
, this is the expected JSON response:
{
"status": "OK",
"timestamp": "2024-10-20T12:34:56+00:00"
}
This simple health check can be extended to include real checks for your database connection, cache, or external services. We can also add custom statuses or metadata (e.g., version information) in the response as needed.
Here’s a quick example to extend the health check to verify a database connection:
<?php
class HealthCheckMiddleware implements MiddlewareInterface
{
private $dbConnection;
public function __construct($dbConnection)
{
$this->dbConnection = $dbConnection;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getUri()->getPath() === '/health') {
$status = [
'status' => 'OK',
'timestamp' => (new \DateTime())->format(\DateTime::RFC3339),
];
// Check database connection
try {
$this->dbConnection->query('SELECT 1'); // Simple query to test DB connection
$status['database'] = 'connected';
} catch (\Exception $e) {
$status['database'] = 'disconnected';
}
return new Response(200, ['Content-Type' => 'application/json'], json_encode($status));
}
return $handler->handle($request);
}
}
This version of HealthCheckMiddleware
checks the database connection and includes its status in the response.
Here is a list of useful middlewares that can enhance the functionality, security, and performance:
Authentication Middleware:
Authorization Middleware:
CSRF Protection Middleware:
Input Validation Middleware:
Rate Limiting Middleware:
Logging Middleware:
Error Handling Middleware:
Content Negotiation Middleware:
Accept
headers sent by the client.CORS Middleware:
Cache Middleware:
Cache-Control
andETag
.Compression Middleware:
Security Headers Middleware:
Strict-Transport-Security
,X-Content-Type-Options
,X-Frame-Options
, andContent-Security-Policy
to protect against certain types of attacks.Request Throttling Middleware:
Session Middleware:
Request Tracing Middleware:
Localization Middleware:
ETag Middleware:
ETag
headers to handle caching and determine if a resource has changed, reducing unnecessary data transfers for unchanged resources.IP Whitelisting Middleware:
These middlewares address common concerns in security, performance, usability, and resource management.