笔记:中间件 middleware

中间件主要是提供了一种方便的机制用于过滤进入应用程序的 HTTP 请求。摘自文档
不仅可以过滤 HTTP 请求(前置中间件),也可用于记录日志(后置中间件),添加任务(Terminable中间件) 等。
命令行:php artisan make:middleware TestMiddleware
示例:

    public function handle($request, Closure $next)
    {
        //请求执行之前,过滤http请求
        Log::info('请求之前过滤http请求', []);

        $response = $next($request);

        //请求执行之后
        $response->header('Token', 'this is add token!');       //设置响应头的token
        $response->headers->set('Token1', 'this is add token1!');       //设置响应头的token
        $response->withHeaders([
            'Token2' => 'this is add token2!',
        ]);
        Log::info('controller return 之后', [1, 2, 3]);

        //响应
        return $response;
    }

基于terminate中间件实现慢请求日志:

    public function terminate($request, $response)
    {
        $slowRequest = config('request.slow_request_time');
        $useTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
        $log = [
            'url' => $request->url(),
            'method' => $request->method(),
            'path' => $request->path(),
            'headers' => $request->headers->all(),
            'params' => $request->all(),
            'clientIps' => $request->getClientIps()
        ];
        $info =  $request->path() . ' => userTime:' . $useTime * 1000 . 'ms';
        if ($slowRequest && $useTime > $slowRequest) {
            Log::channel('reqSlowLog')->info($info, $log);
        } else {
            Log::channel('reqLog')->info($info, $log);
        }
    }

配置文件request.php添加配置:

    // 慢请求日志时间
    'slow_request_time' => env('SLOW_REQUEST_TIME', 0),
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!