执行处理一个静态文件

@param string                $request_uri
@param \Swoole\Http\Request  $request
@param \Swoole\Http\Response $response
186009
public static function exec($request_uri, \Swoole\Http\Request $request, \Swoole\Http\Response $response)
    {

        $filename = APP_PATH . "/public{$request_uri}";
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        // 发送Mime
        $comm_response = new Response($response);
        $contentType = $comm_response->contentType($extension);

        $config = AgileCore::getInstance()->getConfig('statics');



        // 浏览器缓存 && \Comm\Misc::isProEnv()
        if (isset($config['expire']) && $config['expire'] > 0) {
            $response->header('Cache-control', "max-age={$config['expire']}");
        }

        if (method_exists($response, 'gzip')) {
            $response->gzip(1);
        }

        self::_sendfile($filename, $response, $contentType);

    }
507143
public function _loadDummyData( &$headers, &$response, &$response_code )
	{
		$data = @file_get_contents($this->_getDummyDataFileName());
		$data = @unserialize($data);
		if (!$data)
			throw new RequestException("No DummyData available for call. File '{$this->_getDummyDataFileName()}' failed to be parsed.");

		$headers       = $data['headers'];
		$response      = $data['response'];
		$response_code = $data['code'];
	}
530173
public function run(Request $request, Response $response)
    {
        $this["logger.service"]("System")->info("Beginning process for request.", [$request]);

        $this->setRequestProperties($request);

        $result = $this["hooks.service"]->exec(
            "application.dispatch.before",
            $request,
            $response,
            $this
        );
        if ($result === "exit"
            || (is_array($result) && in_array("exit", $result))) {
            return;
        }

        // record the time before execution
        $start = microtime(true);

        // dispatch request
        try {
            $this["routeDispatcher.service"]->dispatch($request, $response, $this);
        } catch (RouteNotFoundException $routeNotFound) {
            $this["logger.service"]("System")->error("No Route found for Request");
            $this["logger.service"]("System")->debug(
                "No Route Found Debug Information",
                ["exception" => $routeNotFound]
            );

            $response->setStatusCode(404);
            $response->setContent($this->load404Page());
            throw $routeNotFound;
        }

        $this["logger.service"]("System")->info(
            "Request has finished processing, Response is ready to be sent to "
            . "caller."
        );

        $this["hooks.service"]->exec("application.dispatch.after");

        // record the time after execution
        $end = microtime(true);
        $this["logger.service"]("System")->debug(
            "Time taken to finish Request processing",
            [
                "start"     =>  $start,
                "end"       =>  $end,
                "elapsed"   =>  $end - $start,
                "uri"       =>  $request->getRequestUri()
            ]
        );
    }
695841
public function execute(Request $request, Response $response)
    {
      // Open curl handler
      $handle = curl_init();

      // Set header callback
      curl_setopt($handle, CURLOPT_HEADERFUNCTION, array(&$response, 'header'));

      // Do not reuse connection
      curl_setopt($handle, CURLOPT_FORBID_REUSE, 1);
      curl_setopt($handle, CURLOPT_FRESH_CONNECT, 1);

      // Clear default "Expect: 100-continue" header
      //curl_setopt($handle, CURLOPT_HTTPHEADER, array('Expect:'));

      // Set custom headers
      if($request->hasHeaders())
      {
        curl_setopt($handle, CURLOPT_HEADER, 0);
        curl_setopt($handle, CURLOPT_HTTPHEADER, $request->getHeaders());
      }

      // Set authentication if needed
      if($request->hasUsername() && $request->hasPassword())
      {
        curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($handle, CURLOPT_USERPWD, $request->getUsername() . ':' . $request->getPassword());
      }

      // Set timeout
      if($request->hasTimeout())
        curl_setopt($handle, CURLOPT_TIMEOUT, $request->getTimeout());

      // Set curl options
      curl_setopt($handle, CURLOPT_URL, $request->getUrl());
      curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);

      curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
      //curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
      curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);

      curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1);

      // Get method
      $method = $request->getMethod();

      if(!method_exists($this, strtolower($method)))
        throw new Exception(__METHOD__ . '; Request method "' .$method . '" not supported');

      // Call request method handler
      call_user_func(array($this, strtolower($method)),  $handle, $request, $response);

      // Execute curl request
      curl_exec($handle);

      // Get info
      $info = curl_getinfo($handle);

      // Set info
      $response->setInfo($info);

      // Close curl handler
      if(!is_null($handle) && is_resource($handle))
        curl_close($handle);
    }
794388
public function onRequest(Request $request, Response $response)
    {
        try {
            // 处理 406
            $responder = $this->getResponder();

            if ($responder->getAcceptHandler($request) === null) {
                throw ProtocolException::notAcceptable(
                    $request->getHeaderLine('Accept'),
                    $request->getProtocol()
                );
            }

            $response = $this->handle($request, $response);
        } catch (MiddlewareException $e) {
            // {{ log
            $this->logger->error(
                sprintf('中间件 %s 发生异常', $e->getMiddleware()),
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode()
                ]
            );
            // }}

            $response = $responder(
                $request,
                $response,
                new Payload(
                    500,
                    $e->getMessage()
                )
            );
        } catch (ProtocolException $e) {
            // {{ log
            $this->logger->error(
                sprintf('处理 %s 请求发生异常', strtoupper($e->getProtocol())),
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode(),
                    'uri' => $request->getRequestTarget(),
                ]
            );
            // }}

            $response = $e->makeResponse($request, $response, $responder);
        } catch (Exception $e) {
            // {{ log
            $this->logger->error(
                '系统错误',
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode()
                ]
            );
            // }}

            $response = $responder(
                $request,
                $response,
                new Payload(
                    500,
                    $e->getMessage()
                )
            );
        }

        unset($responder);

        return $response->end();
    }
482555
public function launch(Request $request, Response $response)
    {
        if (count($this->routes) === 0) {
            throw new \RuntimeException("No routes defined");
        }

        $this->uri = $request->httpRequest->getPath();

        if ($this->uri = null) {
            $this->uri = "/";
        }

        $request->on('end', function () use (&$request, &$response) {
            $this->matchRoutes($request, $response);  
        });

        $request->on('error', function ($error) use (&$request, &$response) {
            $this->emit('error', [$request, $response, $error]);
        });

        $request->parseData();
    }
76675
protected function sendResetResponse(Request $request, $response)
    {
        if ($request->expectsJson()) {
            return response()->json([
                'status' => trans($response)
            ]);
        }
        return redirect($this->redirectPath())
            ->with('status', trans($response));
    }
1196453
public function record(Request $request, Response $response)
    {
        if ($this->hasResponse($request)) {
            return;
        }

        $recording = array(
            'request'  => $request->toArray(),
            'response' => $response->toArray()
        );

        $this->storage->storeRecording($recording);
    }
831211
public function sendFile($path, $request, $response)
    {
        if (empty($path)) {
            $path = __DIR__ . '/Views/index.html';
            if (!$response->sendfile($path)) {
                swoole_async_readfile($path, function ($filename, $content) use ($response) {
                    $response->end($content);
                });
            }

            return Macro::SEND_FILE_200;
        }

        $path = realpath(urldecode($path));
        $root = $this->config['http']['domain'][$this->route->getHost()]['root'] ?? null;

        // 判断文件是否存在
        if (!file_exists($path)) {
            $response->status(404);
            $response->end('');
            return Macro::SEND_FILE_404;
        }

        // 判断文件是否有权限（非root目录不能访问）
        if (empty($root) || strpos($path, $root) === false) {
            $response->status(403);
            $response->end('');
            return Macro::SEND_FILE_403;
        }

        $info      = pathinfo($path);
        $extension = strtolower($info['extension'] ?? '');

        // 判断缓存
        $lastModified = gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT';
        if (isset($request->header['if-modified-since']) && $request->header['if-modified-since'] == $lastModified) {
            $response->status(304);
            $response->end('');
            return Macro::SEND_FILE_304;
        }

        $normalHeaders = getInstance()->config->get("fileHeader.normal", ['Content-Type: application/octet-stream']);
        $headers       = getInstance()->config->get("fileHeader.$extension", $normalHeaders);

        foreach ($headers as $value) {
            list($hk, $hv) = explode(': ', $value);
            $response->header($hk, $hv);
        }

        $response->header('Last-Modified', $lastModified);
        if (!$response->sendfile($path)) {
            swoole_async_readfile($path, function ($filename, $content) use ($response) {
                $response->end($content);
            });
        }

        return Macro::SEND_FILE_200;
    }
1313206
public function terminate(Request $request, $response)
    {
        if ($this->isLaravel()) {
            $this->getKernel()->terminate($request, $response);

            return;
        }

        $app = $this->getApplication();
        $reflection = new \ReflectionObject($app);

        $middleware = $reflection->getProperty('middleware');
        $middleware->setAccessible(true);

        $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware');
        $callTerminableMiddleware->setAccessible(true);

        if (count($middleware->getValue($app)) > 0) {
            $callTerminableMiddleware->invoke($app, $response);
        }
    }
47124
private function getDownloadResponse(Request $request, Response $response)
    {
        try {
            $videoUrls = $this->video->getUrl();
        } catch (EmptyUrlException $e) {
            /*
            If this happens it is probably a playlist
            so it will either be handled by getStream() or throw an exception anyway.
             */
            $videoUrls = [];
        }
        if (count($videoUrls) > 1) {
            return $this->getRemuxStream($request, $response);
        } elseif ($this->config->stream && (isset($this->video->entries) || $request->getQueryParam('stream'))) {
            return $this->getStream($request, $response);
        } else {
            if (empty($videoUrls[0])) {
                throw new Exception(_("Can't find URL of video."));
            }

            return $response->withRedirect($videoUrls[0]);
        }
    }
1019444
public function resolve(Request $request, Response $response, UriPath $uriPath)
    {
        if ($this->target instanceof HttpUri) {
            $targetUri = $this->target;
        } else {
            $targetUri = $request->uri()->withPath($this->target);
        }

        $response->redirect($targetUri, $this->statusCode);
    }
981026
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8"); 
        response.setCharacterEncoding("UTF-8"); 
        request.setCharacterEncoding("UTF-8");
        
        String questionStr = request.getParameter("q");
        String n = request.getParameter("n");
        int topN = -1;
        if(n != null && StringUtils.isNumeric(n)){
            topN = Integer.parseInt(n);
        }
        Question question = null;
        List<CandidateAnswer> candidateAnswers = null;
        if (questionStr != null && questionStr.trim().length() > 3) {
            question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr);
            if (question != null) {
                candidateAnswers = question.getAllCandidateAnswer();
            }
        }
        LOG.info("问题："+questionStr); 
        try (PrintWriter out = response.getWriter()) {
            String json = JsonGenerator.generate(candidateAnswers, topN);
            out.println(json);
            LOG.info("答案："+json);
        }
    }
1197861
protected function setUriHeader(Request $request, Response $response)
    {
        $response->headers->set('X-PJAX-URL', $request->getUrl());

        return $this;
    }
1374033
public function run(Request $request, Response $response)
    {
        $this->initController($request, $response);
        $event = $this->eventDispatcher->raiseEvent(
            $this->createLoadedEvent()
        );

        if ($event->isHandled() && $event->getResponse() instanceof Response) {
            return $event->getResponse();
        }

        $this->eventDispatcher->raiseEvent(
            $this->createFinishedEvent(
                $this->runController($request, $response)
            )
        );

        return $response;
    }
135372
public function doFilter(Request $request, Response $response)
    {
        if ((int) $request->get('error') === 1) {
            return
                $response
                    ->withStatusCode(404)
                    ->write('error')
            ;
        }
    }
287111
private function parseRequestUri(): void
    {
        $requestUri = $this->baseClass->getRequestUri();
        $path = \explode('/', $requestUri);
        $pathCnt = \count($path);
        if ($pathCnt > 0) {
            $file = \array_pop($path);
            $path = \sprintf('%%DOCUMENT_ROOT%%%s%s', \implode(DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
            $path = $this->baseClass->parsePath($path);

            $file = \explode('.', $file);
            $ext = '';

            if (\count($file) > 1) {
                $ext = \array_pop($file);
            }

            $file = \explode('__', \implode('.', $file));
            $resizeParams = [];

            if (\count($file) > 1) {
                $resizeParams = $this->parseResizeParams(\explode('_', $file[1]));
            }

            $file = $file[0];

            $this->uriParams['path'] = $path;
            $this->uriParams['file'] = $file;
            $this->uriParams['extension'] = $ext;
            $this->uriParams['resize-params'] = $resizeParams;
        }
    }