diff --git a/src/Http/Middleware/CorrelationId.php b/src/Http/Middleware/CorrelationId.php index 0959dce..ef354c4 100644 --- a/src/Http/Middleware/CorrelationId.php +++ b/src/Http/Middleware/CorrelationId.php @@ -19,9 +19,13 @@ public function handle(Request $request, Closure $next): Response { $cfg = config('microservice.correlation'); $header = $cfg['header']; + $length = (int) ($cfg['length'] ?? 36); - // Use existing header or generate a new UUID - $id = $request->header($header) ?: Str::uuid()->toString(); + // Use existing header or generate a new ID of the configured length + $id = $request->header($header); + if (! $id) { + $id = Str::random($length); + } // Set on request and response $request->headers->set($header, $id); diff --git a/tests/Middleware/CorrelationIdTest.php b/tests/Middleware/CorrelationIdTest.php new file mode 100644 index 0000000..bbbc5b8 --- /dev/null +++ b/tests/Middleware/CorrelationIdTest.php @@ -0,0 +1,40 @@ +set('microservice.correlation.header', $header); + config()->set('microservice.correlation.length', $length); + + Route::middleware(CorrelationId::class)->get('/correlation-default', fn () => response()->json(['ok' => true])); + + $response = $this->get('/correlation-default'); + + $this->assertSame($length, strlen($response->headers->get($header))); + } + + /** @test */ + public function it_generates_configured_length_correlation_id() + { + $header = 'X-Correlation-ID'; + $length = 20; + config()->set('microservice.correlation.header', $header); + config()->set('microservice.correlation.length', $length); + + Route::middleware(CorrelationId::class)->get('/correlation-custom', fn () => response()->json(['ok' => true])); + + $response = $this->get('/correlation-custom'); + + $this->assertSame($length, strlen($response->headers->get($header))); + } +}