Created
February 24, 2023 14:42
-
-
Save mortenscheel/bdb010ba05921b51f6419959203defc8 to your computer and use it in GitHub Desktop.
Write raw request and response to file with Laravel's Http client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use GuzzleHttp\Middleware; | |
use Illuminate\Support\Facades\Http; | |
use Illuminate\Support\ServiceProvider; | |
class AppServiceProvider extends ServiceProvider | |
{ | |
public function boot() | |
{ | |
Http::macro('record', function(string $path, bool $append = true) { | |
return $this->withMiddleware(Middleware::tap(after: function($request, $options, $promise) use ($path, $append) { | |
$fh = fopen($path, $append ? 'ab+' : 'wb'); | |
$record = fn(string $line, bool $newline = true) => fwrite($fh, $line . ($newline ? PHP_EOL : '')); | |
$record(sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion())); | |
foreach ($request->getHeaders() as $name => $values) { | |
$record(sprintf('%s: %s', $name, implode(', ', $values))); | |
} | |
$record(''); | |
while ($request->getBody()->eof() !== true) { | |
$record($request->getBody()->read(1024), false); | |
} | |
$response = $promise->wait(true); | |
$record(sprintf('HTTP/%s %d %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase())); | |
foreach ($response->getHeaders() as $name => $values) { | |
$record(sprintf('%s: %s', $name, implode(', ', $values))); | |
} | |
$record(''); | |
while ($response->getBody()->eof() !== true) { | |
$record($response->getBody()->read(1024), false); | |
} | |
fclose($fh); | |
})); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
storage/app/request.txt