webman:使用路由中间件(v1.5.7)

发布时间 2023-08-23 10:01:11作者: 刘宏缔的架构森林

一,官方文档:

https://www.workerman.net/doc/webman/middleware.html

二,php代码:

1,配置路由的中间件

config/route.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
 
use Webman\Route;
 
//指定默认页面
Route::get('/', [app\controller\IndexController::class, 'index']);
 
//组路由
Route::group('/image', function () {
    Route::get('/list', [app\controller\ImageController::class,'list'])->middleware([
    app\middleware\CheckIp::class,
]);
    Route::get('/detail', [app\controller\ImageController::class,'detail']);
    Route::get('/comment', [app\controller\ImageController::class,'comment']);
 
    Route::post('/add', [app\controller\ImageController::class,'add']);
});
 
//自定义404的json返回
Route::fallback(function(){
    return json(['code' => 404, 'msg' => '404 not found']);
});
 
//关闭默认路由
Route::disableDefaultRoute();

2,中间件:

app/middleware/CheckIp.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
namespace app\middleware;
 
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\result\Result;
 
class CheckIp implements MiddlewareInterface
{
    //地址列表,生产环境中通常会存放在redis中
    private $ipList = ['192.168.219.1','127.0.0.2'];
 
    public function process(Request $request, callable $handler) : Response
    {
 
         //检查ip是否匹配
        $ip = $request->getRemoteIp();
        if(in_array($ip,$this->ipList)){
            return Result::ErrorCode(100,"IP地址错误");
        }
 
        echo '这里是请求穿越阶段,也就是请求处理前';
        //开始时间
        $startTime = microtime(true);
 
        $response = $handler($request); // 继续向洋葱芯穿越,直至执行控制器得到响应
 
        echo '这里是响应穿出阶段,也就是请求处理后';
 
        return $response;
    }
}

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/08/21/webman-shi-yong-lu-you-zhong-jian-jian/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,测试效果:

当访问ip匹配数组时,

四,查看webman版本:

liuhongdi@lhdpc:/data/webman/imageadmin$ composer show workerman/webman-framework
name     : workerman/webman-framework
descrip. : High performance HTTP Service Framework.
keywords : High Performance, http service
versions : * v1.5.7
...