fqapps / swoole-gin
teaching repo
v1.0.2
2022-04-29 10:03 UTC
Requires
- php: ^8.0
- ext-swoole: *
- guzzlehttp/guzzle: 7.4.x-dev
- psr/http-client: 1.0.x-dev
- psr/http-message: ^1.0.1
- psr/http-server-handler: ^1.0.1
- psr/http-server-middleware: ^1.0.1
- psr/log: ^3.0.0
- symfony/dotenv: ^6.0
- symfony/serializer: 6.0.x-dev
Requires (Dev)
- phpunit/phpunit: ^9.5.19
- psalm/plugin-phpunit: ^0.16.1
- swoole/ide-helper: ^4.8
- vimeo/psalm: ^4.22.0
README
Teaching warehouse
中文
Document
How to install
$ composer require swoole/swoole-gin
Usage
declare(strict_types=1); use SwooleGin\Gin\Context\Context; use SwooleGin\Gin\Context\ContextHandlerFuncInterface; use SwooleGin\Gin\Gin; use SwooleGin\Gin\Middleware\FaviconMiddleware; use SwooleGin\Options; use SwooleGin\Server; use SwooleGin\Stream\StringStream; use SwooleGin\Utils\HTTPStatus; include_once __DIR__ . '/../vendor/autoload.php'; $servOpts = new Options(); $servOpts->setAddr('0.0.0.0:8082'); $serv = new Server($servOpts); $engine = new Gin(); $engine->use( (new FaviconMiddleware), // 假鉴权中间件 (new class implements ContextHandlerFuncInterface { public function __invoke(Context $context) { if ($context->query('token') !== '123456') { $context->response->withBody(new StringStream('authorized failed')); $context->response->withStatus(HTTPStatus::StatusForbidden); $context->abort(); } } }), // 用于模拟洋葱结构中间件:打印响应内容 (new class implements ContextHandlerFuncInterface { public function __invoke(Context $context) { $context->next(); $body = $context->response->getBody()->getContents(); echo 'resp:', $body, PHP_EOL; $context->response->withBody(new StringStream($body)); } }), ); $engine->GET('/hello', (new class implements ContextHandlerFuncInterface { public function __invoke(Context $context) { $context->Raw(HTTPStatus::StatusOK, 'hello world'); } })); $engine->setOnNotFound((new class implements ContextHandlerFuncInterface { public function __invoke(Context $context) { $context->JSON(HTTPStatus::StatusOK, ['code' => HTTPStatus::StatusNotFound, 'msg' => 'not found']); } })); $serv->setHandler($engine); // server run $serv->serve();
todo
- middleware
- context
- gin-router