protected function setGateway($gateway = null)
    {
        $deferred = new Deferred();

        $buildParams = function ($gateway) use ($deferred) {
            $params = [
                'v'        => self::GATEWAY_VERSION,
                'encoding' => $this->encoding,
            ];

            $query         = http_build_query($params);
            $this->gateway = trim($gateway, '/').'/?'.$query;

            $deferred->resolve($this->gateway);
        };

        if (is_null($gateway)) {
            $this->http->get('gateway')->then(function ($response) use ($buildParams) {
                $buildParams($response->url);
            }, function ($e) use ($buildParams) {
                // Can't access the API server so we will use the default gateway.
                $buildParams('wss://gateway.discord.gg');
            });
        } else {
            $buildParams($gateway);
        }

        $deferred->promise()->then(function ($gateway) {
            $this->logger->info('gateway retrieved and set', ['gateway' => $gateway]);
        }, function ($e) {
            $this->logger->error('error obtaining gateway', ['e' => $e->getMessage()]);
        });

        return $deferred->promise();
    }