SimpleServerCoroutine.php 1.5 KB
<?php

namespace jytools;

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Coroutine\Http\Server;

class SimpleServerCoroutine
{
    private Server $httpServer;
    public function __construct($host, $port, $ssl = false)
    {
        $this->httpServer = new Server($host, $port, $ssl);
    }
    public function router($method, $path, $callback)
    {
        $this->httpServer->handle($path, function (Request $request, Response $response) use ($method, $callback) {
            $m = $request->getMethod();
            if (!in_array($m, $method)) {
                $response->status(405);
                $response->end();
                return;
            }
            $requestInfo = [
                'path' => $request->server['path_info'],
                'uri' => $request->server['request_uri'],
                'get' => $request->get ?: [],
                'post' => $request->post ?: [],
                'method' => $request->getMethod(),
                'header' => $request->header ?: [],
                'cookie' => $request->cookie ?: [],
            ];
            $simpleRequest = new SimpleRequest($requestInfo);
            $res = call_user_func($callback, $simpleRequest);
            if (empty($res)) {
                $response->end(json_encode(['code' => -1, 'msg' => 'nothing return']));
            } else {
                $response->end($res);
            }
        });
    }

    public function start()
    {
        $this->httpServer->start();
    }
}