您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
webman-中间件-中间件接口及示例
发布时间:2022-01-19 22:39:37编辑:雪饮阅读()
用到curl命令及相关参数
curl
参数:
--location:跟踪重定向
--request:指定要使用的请求命令
--header:要传递到服务器的行自定义标头(H)(就是自定义请求头咯)
-d:post请求时候传参使用,若为post请求,就算不传递任何post数据,也要使用-d ''表示不传递任何数据,否则就没有回显(可能与服务端实现有关,也可能与curl版本有关,没有深究)
实例:用户身份验证中间件
config/route.php路由配置:
<?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('/blog/index', [app\controller\Foo::class, 'index'])->middleware([app\middleware\AuthCheckTest::class]);
Route::post('/blog/login', [app\controller\Foo::class, 'login']);
Route::get('/blog/loginPage', [app\controller\Foo::class, 'loginPage']);
Route::fallback(function(){
return json(['code' => 404, 'msg' => '404 not found']);
});
\app\middleware\AuthCheckTest.php中间件:
<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class AuthCheckTest implements MiddlewareInterface
{
public function process(Request $request, callable $next) : Response
{
$session = $request->session();
if (!$session->get('userinfo')) {
return redirect('/blog/loginPage');
}
return $next($request);
}
}
\app\controller\Foo.php控制器实现:
<?php
namespace app\controller;
use support\Request;
class Foo
{
/**
* 该方法会在请求前调用
*/
public function beforeAction(Request $request)
{
echo 'beforeAction';
// 若果想终止执行Action就直接返回Response对象,不想终止则无需return
// return response('终止执行Action');
}
/**
* 该方法会在请求后调用
*/
public function afterAction(Request $request, $response)
{
echo 'afterAction';
// 如果想串改请求结果,可以直接返回一个新的Response对象
// return response('afterAction');
}
public function index(Request $request)
{
return response("welcomeing");
}
public function login(Request $request)
{
$session = $request->session();
$session->set('userinfo', ["user_name"=>"kasumi"]);
return response('login success');
}
public function loginPage(Request $request){
return response("this is loginPage \n");
}
}
请求实例:
直接访问首页:
[root@localhost ~]# curl --location --request GET 'http://192.168.31.53:8787/blog/index' --header 'Cookie: PHPSID=718f6501f179d84119190e97'
this is loginPage
请求一次登录:
[root@localhost ~]# curl --location --request POST 'http://192.168.31.53:8787/blog/login' -d '' --header 'Cookie: PHPSID=718f6501f179d84119190e97'
login success
再次访问首页:
curl --location --request GET 'http://192.168.31.53:8787/blog/index' --header 'Cookie: PHPSID=718f6501f179d84119190e97'
关键字词:webman,中间件,接口,示例