ctw / ctw-middleware-generatedby
This PSR-15 middleware adds an X-Generated-By UUID v5 to the Response header.
Requires
- php: ^8.3
- ctw/ctw-middleware: ^4.0
- laminas/laminas-diactoros: ^2.11
- psr/container: ^1.0 || ^2.0
- ramsey/uuid: ^4.1
Requires (Dev)
- ctw/ctw-qa: ^4.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^1.7
- phpstan/phpstan-phpunit: ^1.1
- phpstan/phpstan-strict-rules: ^1.3
- phpunit/phpunit: ^10.0
- squizlabs/php_codesniffer: ^3.6
- symfony/var-dumper: ^7.0
README
PSR-15 middleware to create a UUID v5 (Universally Unique Identifiers) and add it to the X-Generated-By
header of the response. The UUID is created using the server IP address i.e. $_SERVER['SERVER_ADDR']
and domain name of the application i.e. $_SERVER['SERVER_NAME']
.
This functionality is useful when multiple applications servers are running behind a load balancer. By inspecting the X-Generated-By
header, it is possible to find out exactly which application server processed the request without exposing its public IP addresses.
middlewares/utils provides utility classes for working with PSR-15 and ramsey/uuid provides UUID v5 generation.
Installation
Install the middleware using Composer:
$ composer require ctw/ctw-middleware-generatedby
Standalone Example
use Ctw\Middleware\GeneratedByMiddleware\GeneratedByMiddlewareFactory; use Laminas\ServiceManager\ServiceManager; use Middlewares\Utils\Dispatcher; use Middlewares\Utils\Factory; $container = new ServiceManager(); $factory = new GeneratedByMiddlewareFactory(); $generatedByMiddleware = $factory->__invoke($container); $serverParams = [ 'SERVER_ADDR' => '1.1.1.1', 'SERVER_NAME' => 'www.example.com', ]; $request = Factory::createServerRequest('GET', '/', $serverParams); $stack = [ $generatedByMiddleware, ]; $response = Dispatcher::run($stack, $request); $uuid = $response->getHeaderLine('X-Generated-By'); dump($uuid); // 78ac0e14-0f2b-529e-81e2-a0f50f6029c5
Example in Mezzio
The middleware has been extensively tested in Mezzio.
After using Composer to install, simply make the following changes to your application's configuration.
In config/config.php
:
$providers = [ // [..] \Ctw\Middleware\GeneratedByMiddleware\ConfigProvider::class, // [..] ];
In config/pipeline.php
:
use Ctw\Middleware\GeneratedByMiddleware\GeneratedByMiddleware; use Mezzio\Application; use Mezzio\MiddlewareFactory; use Psr\Container\ContainerInterface; return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container): void { // [..] $app->pipe(GeneratedByMiddleware::class); // [..] };
You can then test to ensure that the X-Generated-At
header is in the returned HTTP headers with:
curl -I -k https://www.example.com.development
If you see the X-Generated-At
header, the middleware is correctly installed:
date: Wed, 17 Mar 2021 05:59:26 GMT
x-generated-by: ce9f95cf-9ce3-5c0d-8c59-c579f2e474fb
content-type: text/html; charset=utf-8