Adding Guzzle Client Middleware to use proxy based on request URL in Laravel

24 Views Asked by At

I'm using Guzzle HTTP client for making requests from my Laravel 10 application. I want to use a proxy for some URLs, thought about doing so with middleware. Thing is, in order to intercept the request and check its URL I already created a middleware. Then, if I add a middleware from the previous one's callback, I'll be adding it on every call, and the first one seems to skip the proxy.

My current code:

$stack = HandlerStack::create();

$stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($stack) {
    if (strpos($request->getUri(), "string") !== false) {
        $stack->push(function (callable $handler) use ($proxy) {
            return function (RequestInterface $request, array $options) use ($handler, $proxy) {
                $options['proxy'] = $proxy;
                return $handler($request, $options);
            };
        });

    }

    return $request;
});

$client = new Client(['handler' => $stack]);

Any idea how I can make it work from the first call, without pushing the same middleware over and over?

0

There are 0 best solutions below