如何实现真正的全局中间件

ziyoren

问题描述

期望通过一个全局中间件在响应的header里添加服务节点信息,但某些情况下并未执行全局中间件。

项目相关文件如下:

自定义中间件

<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AllinMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        $response = $handler($request);
        $response->withHeaders([
            'Via' => config('app.name', 'ziyo.bot') . '/' . config('app.version', '1.0.0'),
        ]);
        return $response;
    }
}

启用自定义中间件 config\middleware.php

<?php

return [
    '' => [
        app\middleware\AllinMiddleware::class,
    ]
];

路由配置文件 config\route.php

<?php

use Webman\Route;
use Webman\Http\Response;

// 被定义的路由会执行全局中间件
Route::get('/', function () {
    return 'Hello Webman!';
});

// 这里的请求未执行中间件
Route::fallback(function(){
    $data = ['code' => 404, 'msg' => '404 not found'];
    $options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
    return new Response(404, ['Content-Type' => 'application/json'], json_encode($data, $options));
});

Route::disableDefaultRoute();

为此你搜索到了哪些方案及不适用的原因

Route::fallback 是否可以指定一下中间件,或执行全局中间件

389 1 0
1个回答

walkor

正常情况下404请求就不应该被业务感知,因为访问不存在的地址。404请求也不应该走中间件,因为中间件预期都是处理正常的请求,404弄进来可能会导致业务异常。

  • ziyoren 2024-07-05

    可以理解。

    就目前的需求,我在中间件里写了个静态方法,在404里调用一下,也能实现。

×
🔝