Skip to content

中间件 ​

中间件是在请求到达控制器之前或响应返回客户端之前执行的过滤器。Kuiper Web 模块提供灵活的中间件系统,支持全局和路由级别的中间件。

中间件概念 ​

什么是中间件 ​

中间件是一个拦截 HTTP 请求和响应的组件,可以:

  • 请求前处理: 验证、认证、日志记录等
  • 请求后处理: 修改响应、添加头部等
  • 中断请求: 权限不足时返回错误响应

中间件执行顺序 ​

text
请求 → 中间件1 → 中间件2 → ... → 控制器
                                    ↓
响应 ← 中间件1 ← 中间件2 ← ... ← 控制器

洋葱模型

中间件采用洋葱模型:请求时从外向内进入,响应时从内向外返回。

内置中间件 ​

AccessLog 访问日志中间件 ​

kuiper\web\middleware\AccessLog 按 CLF(Common Log Format) 风格把每个请求 写成一行访问日志:

text
127.0.0.1 - - [03/Dec/2026:03:07:25 +0000] "GET 127.0.0.1:9801/ HTTP/1.1" 200 27 "" "" "-" rt=1.6 {"query":""} {"pid":1072023}

日志文件默认落在 {application.logging.path}/access.log,行格式可用 application.web.log_sample_rate 之外的自定义 formatter 覆盖(见下文「自定义 formatter」)。

相关配置 ​

配置键环境变量默认值说明
application.web.access_log_enabledWEB_ACCESS_LOG_ENABLEDtrue访问日志总开关,关闭后 web 与 RPC 请求都不记录
application.web.access_log_include_rpcWEB_ACCESS_LOG_INCLUDE_RPCtrueRPC HTTP 请求(POST /rpc)是否计入访问日志
application.web.log_fileWEB_LOG_FILE{application.logging.path}/access.log访问日志文件路径
application.web.log_sample_rateWEB_LOG_SAMPLE_RATE1.0采样率,取值 (0, 1],1 表示全部记录
application.web.log_post_bodyWEB_LOG_POST_BODYfalse是否记录请求体(仅 web 表单/JSON 请求有意义)

RPC 请求也计入访问日志 ​

装了 kuiper/rpc 的应用里,POST /rpc 的 JSON-RPC 请求同样写入访问日志, 与 web 请求同一个文件、同一种格式——运维不需要为 RPC 单独配置一套日志:

text
127.0.0.1 - - [03/Dec/2026:03:07:25 +0000] "POST 127.0.0.1:9801/rpc HTTP/1.1" 200 89 "" "" "-" rt=0.49 {"query":""} {"pid":1072023}

为什么路径就能区分

CLF 格式的请求行本身就带路径(POST .../rpc),web 请求与 RPC 请求天然可分; 协议(HTTP/1.1)、状态码与耗时(rt=,毫秒)用的是同一套字段,不需要第二种格式。

RPC 的成败看 RPC 层日志

JSON-RPC 的业务错误在 HTTP 层仍返回 200(协议规定:错误信息在响应体的 error 字段里),因此访问日志里的 200 不代表 RPC 调用成功。RPC 的 业务成败由 RPC 语义层访问日志(kuiper\rpc\server\middleware\AccessLog, 默认启用)记录,两层日志互补:

日志层次内容默认文件
application.web.log_fileHTTP 传输层路径、状态码、耗时、来源 IP(RPC 与 web 混在一起){application.logging.path}/access.log
RPC 语义层访问日志RPC 调用层服务名、方法名、耗时、业务成败、失败原因类型{application.logging.path}/rpc-access.log

两层各自独立:传输层用 application.web.access_log_enabled / access_log_include_rpc 控制;语义层用 application.rpc.access_log_enabled 控制、application.rpc.log_sample_rate 采样(失败请求不参与采样), 详见 RPC 服务端文档的访问日志章节。

什么时候关掉 RPC 记录

RPC 流量远大于 web 流量时(如内部服务间调用 QPS 很高),有三种收敛方式: 关掉传输层的 application.web.access_log_include_rpc、用 application.web.log_sample_rate 采样传输层、或用 application.rpc.log_sample_rate 采样语义层(失败请求始终记录, 采样不会丢掉业务失败的告警信号)。

开启 log_post_body 时注意 RPC 参数

application.web.log_post_body 开启后请求体会被记录,RPC 请求也不例外—— 记下来的是 JSON-RPC 报文原文(含业务参数)。若参数含敏感信息,请关闭该开关 或改用 RPC 层的 kuiper\rpc\server\middleware\SensitiveDataMaskingMiddleware。

哪些 RPC 请求会被记录

记录的是真正进入 JSON-RPC 处理的请求:

  • POST /rpc(命中 application.rpc.server.paths 的路径)——记录;
  • RPC 端点自身的 404 / 405(方法不对、路径不在 paths 内)——不记录, 它们由 RPC 应用直接拒绝,未进入 JSON-RPC 处理;
  • 纯 RPC 部署(入口是 JsonRpcHttpApplication)下的健康检查路径 (/、/status.html、/health)——不记录,避免探针流量刷屏。 web + RPC 共存时这些路径按前缀规则落 web 层,由 web 自己的访问日志记录。

自定义 formatter ​

AccessLog 通过容器里的 LogFormatterInterface bean 输出日志行,默认实现是 CLF 风格的 kuiper\web\logging\TextFormatter。在 container.php 里覆盖该 bean 即可换成结构化 JSON(kuiper\web\logging\JsonFormatter)等自定义实现。

WARNING

覆盖 LogFormatterInterface 会同时影响 web 请求与 RPC 请求的访问日志行 (两者共用同一个 formatter 与日志文件)。

CsrfToken 中间件 ​

CSRF(跨站请求伪造)保护中间件:

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\PostMapping;

#[Controller]
class FormController
{
    #[PostMapping("/submit")]
    #[CsrfToken(repeatOk: false)]  // 启用 CSRF 保护(repeatOk 为必填参数)
    public function submit(): array
    {
        return ['submitted' => true];
    }
}

导入正确的属性类

必须使用 kuiper\web\attribute\CsrfToken。kuiper\web\middleware\CsrfToken 是普通中间件类,作为属性标注时会被静默忽略(不报错,但也不生效)。 另外 repeatOk 是构造函数的必填参数,不能写成 #[CsrfToken]。

CSRF 保护重要性

  • CSRF 攻击可以伪装用户身份执行未授权操作
  • 所有修改数据的操作都应该启用 CSRF 保护
  • 使用 GET 方法的请求不需要 CSRF 保护

配置选项 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\PostMapping;

#[Controller]
class WizardController
{
    #[PostMapping("/submit")]
    #[CsrfToken(repeatOk: false)]  // 推荐:token 不能重复使用
    public function submit(): array
    {
        return ['submitted' => true];
    }

    #[PostMapping("/wizard")]
    #[CsrfToken(repeatOk: true)]  // 允许 token 重复使用(不推荐)
    public function multiStep(): array
    {
        return ['step' => 'completed'];
    }
}

安全警告

设置 repeatOk: true 会降低安全性,仅在特殊业务需求(如多步骤向导)时使用。

LoginOnly 中间件 ​

限制只有登录用户才能访问:

php
<?php
use kuiper\web\attribute\LoginOnly;

#[Controller]
class ProfileController
{
    #[GetMapping("/profile")]
    #[LoginOnly]  // 需要登录
    public function profile(): array
    {
        return ['user' => 'current_user'];
    }

    #[GetMapping("/settings")]
    #[LoginOnly]  // 需要登录
    public function settings(): array
    {
        return ['settings' => []];
    }
}

PreAuthorize 中间件 ​

基于权限的访问控制:

php
<?php
use kuiper\web\attribute\PreAuthorize;

#[Controller]
class AdminController
{
    #[GetMapping("/admin/users")]
    #[PreAuthorize(requiredAuthorities: ['ADMIN'])]
    public function listUsers(): array
    {
        return ['users' => []];
    }

    #[PostMapping("/admin/users")]
    #[PreAuthorize(requiredAuthorities: ['ADMIN', 'USER_MANAGER'])]
    public function createUser(): array
    {
        return ['created' => true];
    }

    #[DeleteMapping("/admin/users/{id}")]
    #[PreAuthorize(anyAuthorities: ['ADMIN', 'SUPER_ADMIN'])]
    public function deleteUser(int $id): array
    {
        return ['deleted' => true];
    }
}

权限参数

  • requiredAuthorities: 需要拥有所有指定权限(AND)
  • anyAuthorities: 需要拥有任意一个权限(OR)

RateLimit 中间件 ​

速率限制中间件,防止 API 被滥用:

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\RateLimit;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
class ApiController
{
    #[GetMapping("/api/data")]
    #[RateLimit]  // 默认优先级 512;限流阈值由 RateLimiter 实现决定,见下方说明
    public function getData(): array
    {
        return ['data' => []];
    }

    #[PostMapping("/api/submit")]
    #[RateLimit]
    public function submit(): array
    {
        return ['submitted' => true];
    }
}

#[RateLimit] 的参数与内置限流器

#[RateLimit] 的构造参数只有 priority(中间件优先级,默认 512), 没有 limit / window 参数——写成 #[RateLimit(limit: 100, window: 60)] 会抛 Error: Unknown named parameter $limit。

限流阈值(窗口大小与配额)由 RateLimiterInterface 的实现决定, 框架内置实现为 FixedWindowRateLimiter(固定窗口):

php
<?php
declare(strict_types=1);

use kuiper\web\ratelimit\FixedWindowRateLimiter;

$limiter = new FixedWindowRateLimiter(
    $storage,        // RateLimitStorageInterface 实现
    $keyResolver,    // RequestKeyResolverInterface 实现
    window: 60,      // 窗口大小(秒)
    limit: 100,      // 窗口内配额
);

默认 bean 的窗口与配额取自配置 application.web.rate_limit.window(默认 60 秒) 与 application.web.rate_limit.limit(默认 100),对应环境变量 WEB_RATE_LIMIT_WINDOW / WEB_RATE_LIMIT_LIMIT。

固定窗口的边界语义:窗口按 floor(now / window) * window 切分,窗口边界处 计数重置——相邻窗口交界处的短时间内最多可能放行约 2 倍 limit 的请求。 需要平滑限流时,请自行实现基于请求时间戳集合的 RateLimiterInterface。

SlidingWindowRateLimiter 已标记 @deprecated:它实现的是固定窗口而非滑动窗口, 为修正名实不符才改名为 FixedWindowRateLimiter,两者行为完全一致, 本类仅保留兼容、未来版本移除,请直接使用 FixedWindowRateLimiter。

反向代理部署必须配置 trusted_proxies

默认的 IP 限流键取自 REMOTE_ADDR。应用部署在反向代理(nginx / Ingress) 之后时,所有请求的 REMOTE_ADDR 都是代理 IP,全站会共享同一个限流桶。 需要配置 application.web.trusted_proxies(IP 或 CIDR 网段,环境变量 WEB_TRUSTED_PROXIES)——框架会从 X-Forwarded-For 右侧向左剥离可信 代理链,剥离层数由 trusted_proxy_hops 限制(默认 1,见下文)。注意 X-Forwarded-For 的内容本身可由客户端伪造,可信网段配得越宽、剥离层数 配得越多,采信伪造值的风险越大。

可信代理跳数 trusted_proxy_hops ​

application.web.trusted_proxy_hops(环境变量 WEB_TRUSTED_PROXY_HOPS, 默认 1)限制 X-Forwarded-For 可信链的剥离层数。

跳数含 REMOTE_ADDR 本身:

跳数含义客户端 IP 取值
1(默认)只信任直连代理(nginx / Ingress)这一层X-Forwarded-For 最右一条(直连代理追加的对端地址)
2链路上还有一层可信代理允许在上一条的基础上再向左剥离一条可信条目
n链路上有 n 层可信代理最多向左剥离 n - 1 条可信条目

解析从 X-Forwarded-For 的右侧向左进行:至多剥离「跳数 - 1」条命中可信 列表的条目,跳数用尽或遇到非可信地址即停在该地址。跳数小于 1 的配置值在 装配期被收敛为 1;直接调用 RemoteAddress::setTrustedProxyHops(0) 则抛 InvalidArgumentException。

为什么需要它:X-Forwarded-For 左侧的条目由更早的链路提供,客户端可以 伪造。不设跳数上限的「跳过所有命中可信列表的地址」写法,在可信网段较宽时 (如 k8s 常见的 10.0.0.0/8 同时覆盖 ingress 与 Pod 网段)会把真实 Pod IP 当成代理跳过,转而采信攻击者注入的伪造值——IP 限流键可被完全伪造(全站 共用一个桶,或定向绕过限流)。跳数上限把「能剥离几层」固定下来,伪造值 最多只能影响被剥离后剩下的条目。

宽私网网段会触发启动告警

trusted_proxies 里出现 /8、/16 级别的私网网段(与 10.0.0.0/8、 172.16.0.0/12、192.168.0.0/16 相交、且前缀不大于 16 的 CIDR)时, 启动期会输出告警:

text
[kuiper\web] 可信代理网段 10.0.0.0/8 覆盖大段私网,真实客户端地址也会命中可信列表,IP 限流键可被 X-Forwarded-For 伪造;请收窄网段,并保持 trusted_proxy_hops 为 1(或按实际代理层数设置)

告警经 error_log 输出(装配期还没有可用的 logger)。

收到这条告警说明可信网段本身就覆盖了客户端地址段:真实客户端地址同样 命中可信列表,跳数用尽前剥离掉的条目可能正是攻击者伪造的。把 trusted_proxies 收窄到实际代理所在的网段 / 单个地址才是根治手段——跳数 上限只能限制剥离层数,无法修正一个「把客户端也当成代理」的网段配置。

速率限制响应头

速率限制中间件会在响应中添加以下头部:

  • X-RateLimit-Limit: 请求限制数量
  • X-RateLimit-Remaining: 剩余请求数
  • X-RateLimit-Reset: 限制重置时间

ErrorHandler 错误处理器 ​

#[ErrorHandler] 不是路由级中间件,而是把一个类注册为指定异常的错误处理器 (该属性继承自 Component,由组件扫描自动注册)。被标注的类需要实现 __invoke(Slim 的 ErrorHandlerInterface 签名),通常继承 kuiper\web\handler\AbstractErrorHandler:

php
<?php
declare(strict_types=1);

namespace App\handler;

use App\exception\ValidationException;
use kuiper\web\attribute\ErrorHandler;
use kuiper\web\handler\AbstractErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\ErrorHandlerInterface;

#[ErrorHandler(ValidationException::class)]
class ValidationErrorHandler extends AbstractErrorHandler
{
    public function __construct(
        ErrorHandlerInterface $defaultErrorHandler,
        ResponseFactoryInterface $responseFactory,
    ) {
        parent::__construct($defaultErrorHandler, $responseFactory);
    }

    protected function respondHtml(
        ServerRequestInterface $request,
        \Throwable $exception,
        bool $displayErrorDetails
    ): ResponseInterface {
        return $this->getResponseFactory()->createResponse(422);
    }

    protected function respondApi(
        ServerRequestInterface $request,
        \Throwable $exception,
        bool $logErrors
    ): ResponseInterface {
        return $this->getResponseFactory()
            ->createResponse(422)
            ->withHeader('Content-Type', 'application/json');
    }
}

#[ErrorHandler] 的构造参数是被处理的异常类名(string|string[])。 也可以通过配置 application.web.error.handlers,以 异常类 => 处理器类 的映射注册, 无需在处理器类上标注属性。

中间件属性使用 ​

方法级别中间件 ​

在控制器方法上应用中间件:

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\LoginOnly;
use kuiper\web\attribute\PreAuthorize;
use kuiper\web\attribute\RateLimit;

#[Controller]
class SecureController
{
    #[GetMapping("/secure")]
    #[LoginOnly]
    #[PreAuthorize(requiredAuthorities: ['USER'])]
    #[RateLimit]
    public function secureAction(): array
    {
        return ['data' => 'secure'];
    }
}

类级别中间件 ​

在控制器类上应用中间件,影响所有方法:

php
<?php
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\LoginOnly;

#[Controller]
#[LoginOnly]  // 所有方法都需要登录
class AdminPanelController
{
    #[GetMapping("/admin")]
    public function index(): array
    {
        return ['admin' => 'panel'];
    }

    #[GetMapping("/admin/users")]
    public function users(): array
    {
        return ['users' => []];
    }

    // 所有方法都会先经过 LoginOnly 中间件
}

中间件优先级 ​

路由级别(方法/类上标注)的中间件按优先级升序执行:数值越小越先执行。 (AttributeProcessor 先按 getPriority() 升序排序,再反转后依次 Route::add() 压入 Slim 的 LIFO 栈,反转即补偿了后进先出的压栈顺序,使数值小的中间件落在栈顶、先被执行。)

全局中间件(application.web.middleware)同样按优先级升序执行:数值越小越先执行。

各中间件属性的默认优先级:

中间件属性默认优先级
#[LoginOnly]101
#[RateLimit]512
其他继承 AbstractMiddlewareFactory 的属性(含 #[CsrfToken]、#[PreAuthorize]、自定义属性)1024(工厂默认值)
php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\RateLimit;

#[Controller]
class PriorityController extends AbstractController
{
    use ControllerTrait;

    #[GetMapping("/action")]
    #[CsrfToken(repeatOk: false)]  // 优先级 1024,后执行(数值大的后跑)
    #[RateLimit]                   // 优先级 512,先执行
    public function action(): ResponseInterface
    {
        return $this->json(['done' => true]);
    }
}

优先级规则

  • 路由级与全局中间件一致:优先级数值越小越先执行(升序)
  • AttributeProcessor 内部按 getPriority() 升序排序后反转,再依次 Route::add(); Slim 的路由中间件栈是 LIFO,反转即补偿压栈顺序,使数值小的落在栈顶先执行
  • 工厂默认优先级为 1024(见 kuiper\web\middleware\AbstractMiddlewareFactory 构造函数)
  • 自定义中间件属性可通过构造参数 $priority 覆盖默认值
  • 尽量不要依赖相同优先级中间件之间的执行顺序

自定义中间件 ​

创建中间件类 ​

实现 MiddlewareInterface 接口:

php
<?php
declare(strict_types=1);

namespace App\middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class LoggingMiddleware implements MiddlewareInterface
{
    public function __construct(
        private LoggerInterface $logger
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $startTime = microtime(true);

        // 记录请求
        $this->logger->info('Incoming request', [
            'method' => $request->getMethod(),
            'uri' => (string) $request->getUri(),
        ]);

        // 继续处理请求
        $response = $handler->handle($request);

        // 记录响应
        $duration = microtime(true) - $startTime;
        $this->logger->info('Request completed', [
            'status' => $response->getStatusCode(),
            'duration' => round($duration * 1000, 2) . 'ms',
        ]);

        return $response;
    }
}

创建中间件属性 ​

创建中间件属性类,即可在控制器类/方法上以属性语法使用自定义中间件:

php
<?php
declare(strict_types=1);

namespace App\attribute;

use App\middleware\LoggingMiddleware;
use kuiper\web\middleware\AbstractMiddlewareFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Log\LoggerInterface;

#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)]
class LogRequest extends AbstractMiddlewareFactory
{
    public function __construct(int $priority = 1024)
    {
        parent::__construct($priority);
    }

    public function create(ContainerInterface $container): MiddlewareInterface
    {
        return new LoggingMiddleware(
            $container->get(LoggerInterface::class)
        );
    }
}

使用自定义中间件 ​

php
<?php
use App\attribute\LogRequest;

#[Controller]
class TrackedController
{
    #[GetMapping("/track")]
    #[LogRequest(priority: 10)]
    public function track(): array
    {
        return ['tracked' => true];
    }
}

注册全局中间件 ​

在 src/config.php 中注册全局中间件:

php
<?php
declare(strict_types=1);

return [
    'application' => [
        'web' => [
            // 扁平数组:键为优先级(升序执行)或字符串 id,
            // 值为类名(由容器解析)或已实例化的中间件对象
            'middleware' => [
                100 => \App\middleware\CorsMiddleware::class,
                200 => \App\middleware\LoggingMiddleware::class,
            ],
        ],
    ],
];

自动注入的内置中间件

  • application.web.access_log_enabled 为 true(默认)时自动注入 kuiper\web\middleware\AccessLog(不存在 AccessLogMiddleware 类)
  • application.web.health_check_enabled 为 true 时自动注入 kuiper\web\middleware\HealthyStatus
  • ErrorMiddleware 始终自动添加

以上中间件无需在 application.web.middleware 中重复配置。

中间件模式 ​

认证中间件 ​

构造 JSON 错误响应

中间件中构造 JSON 错误响应可用注入的 ResponseFactoryInterface(框架不存在 JsonResponse 类)。

php
<?php

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthenticationMiddleware implements MiddlewareInterface
{
    public function __construct(
        private readonly ResponseFactoryInterface $responseFactory
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $token = $request->getHeaderLine('Authorization');

        if (!$this->isValidToken($token)) {
            $response = $this->responseFactory->createResponse(401)
                ->withHeader('Content-Type', 'application/json');
            $response->getBody()->write(
                json_encode(['error' => 'Unauthorized'], JSON_UNESCAPED_UNICODE)
            );
            return $response;
        }

        // 将用户信息添加到请求中
        $user = $this->getUserFromToken($token);
        $request = $request->withAttribute('user', $user);

        return $handler->handle($request);
    }

    private function isValidToken(string $token): bool
    {
        return str_starts_with($token, 'Bearer ');
    }

    private function getUserFromToken(string $token): array
    {
        // 解析 token 获取用户信息
        return ['id' => 1, 'name' => 'User'];
    }
}

CORS 中间件 ​

php
<?php
class CorsMiddleware implements MiddlewareInterface
{
    public function __construct(
        private readonly array $allowedOrigins = ['*']
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        // 处理预检请求
        if ($request->getMethod() === 'OPTIONS') {
            return $this->handlePreflightRequest($request);
        }

        $response = $handler->handle($request);

        // 添加 CORS 头部
        return $this->addCorsHeaders($response, $request);
    }

    private function handlePreflightRequest(ServerRequestInterface $request): ResponseInterface
    {
        $response = new Response(200);

        return $this->addCorsHeaders($response, $request);
    }

    private function addCorsHeaders(
        ResponseInterface $response,
        ServerRequestInterface $request
    ): ResponseInterface {
        $origin = $request->getHeaderLine('Origin');

        if (in_array('*', $this->allowedOrigins) || in_array($origin, $this->allowedOrigins)) {
            $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
        }

        return $response
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
            ->withHeader('Access-Control-Max-Age', '86400');
    }
}

响应压缩中间件 ​

php
<?php
class CompressionMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);

        // 检查客户端是否支持压缩
        $acceptEncoding = $request->getHeaderLine('Accept-Encoding');

        if (!str_contains($acceptEncoding, 'gzip')) {
            return $response;
        }

        // 检查响应是否应该压缩
        $contentType = $response->getHeaderLine('Content-Type');

        if (!str_starts_with($contentType, 'application/json')
            && !str_starts_with($contentType, 'text/')) {
            return $response;
        }

        // 压缩响应体
        $body = $response->getBody();
        $body->rewind();
        $content = $body->getContents();
        $compressed = gzencode($content, 6);

        return $response
            ->withBody(new Stream(fopen('php://memory', 'rw')))
            ->withHeader('Content-Encoding', 'gzip')
            ->withHeader('Content-Length', (string) strlen($compressed));
    }
}

中间件最佳实践 ​

1. 保持中间件单一职责 ​

php
<?php
// ✅ 好的做法
class AuthenticationMiddleware { /* 只处理认证 */ }
class LoggingMiddleware { /* 只处理日志 */ }
class RateLimitMiddleware { /* 只处理限流 */ }

// ❌ 不好的做法
class EverythingMiddleware
{
    // 同时处理认证、日志、限流等
}

2. 中间件应该快速执行 ​

php
<?php
declare(strict_types=1);

namespace App\middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

// ✅ 好的做法:快速检查
class AuthMiddleware
{
    public function __construct(
        private readonly ResponseFactoryInterface $responseFactory
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        if (!$this->hasValidToken($request->getHeaderLine('Authorization'))) {
            return $this->responseFactory->createResponse(401);
        }

        return $handler->handle($request);
    }

    private function hasValidToken(string $token): bool
    {
        return str_starts_with($token, 'Bearer ');
    }
}

// ❌ 不好的做法:在请求路径上做数据库查询等耗时操作
class SlowAuthMiddleware
{
    public function process($request, $handler)
    {
        $user = $this->userRepository->findByToken(
            $request->getHeaderLine('Authorization')
        );

        return $handler->handle($request);
    }
}

3. 正确处理请求和响应 ​

php
<?php
class CustomMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        // 1. 请求前处理
        $request = $this->modifyRequest($request);

        // 2. 调用处理器
        $response = $handler->handle($request);

        // 3. 响应后处理
        $response = $this->modifyResponse($response);

        // 4. 返回响应
        return $response;
    }
}

4. 中间件可组合和重用 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\RateLimit;

#[Controller]
class ApiController
{
    #[GetMapping("/api/resource")]
    #[ApiAuth]           // 自定义认证中间件
    #[RateLimit]         // 速率限制(默认优先级 512)
    #[LogApiCall]        // API 日志
    public function getResource(): array
    {
        return ['resource' => 'data'];
    }
}

故障排查 ​

中间件未执行 ​

问题: 中间件没有生效

解决方案:

bash
# 检查中间件是否正确实现 MiddlewareInterface
# 检查中间件属性是否正确应用到方法或类
# 检查中间件优先级是否正确

中间件执行顺序错误 ​

问题: 中间件按错误的顺序执行

解决方案:

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\RateLimit;

#[Controller]
class ActionController
{
    #[GetMapping('/action')]
    #[RateLimit(priority: 100)]     // 数值小的先执行
    #[CsrfToken(repeatOk: false)]   // 后执行
    public function action(): array
    {
        return [];
    }
}

响应被修改 ​

问题: 中间件意外修改了响应

解决方案:

php
<?php
declare(strict_types=1);

namespace App\middleware;

use Psr\Http\Message\ResponseInterface;

class HeaderMiddleware
{
    public function addHeader(ResponseInterface $response): ResponseInterface
    {
        if ($response->getStatusCode() >= 400) {
            // 不修改错误响应
            return $response;
        }

        return $response->withHeader('X-App', 'kuiper');
    }
}

下一步 ​

基于 MIT 许可发布