guzzle-cache-middleware icon indicating copy to clipboard operation
guzzle-cache-middleware copied to clipboard

Not compatible with gmponos/guzzle_logger

Open compwright opened this issue 3 years ago • 2 comments

Since CacheEntry uses PumpStream for the response, attempting to use this middleware with gmponos/guzzle-log-middleware results in the following error:

StringHandler can not log request/response because the body is not seekable/readable.

compwright avatar Aug 23 '22 17:08 compwright

Workaround:

use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\ResponseInterface;

// Without this, we get the following error from the logger middleware:
//
// "StringHandler can not log request/response because the body is not seekable/readable"
//
// It happens because the cache handler returns the body in the form of PumpStream which
// is not rewindable. To fix, we simply read and copy the stream to a rewindable stream.
//
$handler->push(Middleware::mapResponse(
    fn (ResponseInterface $response) => $response->withBody(
        Psr7Utils::streamFor((string) $response->getBody())
    )
));

// Add the cache middleware
$handler->push($cacheMiddleware, 'cache');

compwright avatar Dec 17 '22 03:12 compwright

I'm using the cache middleware w/ gmponos without error. I'm using Monolog rather than StringHandler, so perhaps it's StringHandler specifically that isn't compatible.

intel352 avatar Jan 20 '23 06:01 intel352