SimpleServerCoroutine.php
2.2 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace jiaoyin;
require_once __DIR__ . '/func.php';
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Coroutine\Http\Server;
use function jiaoyin\output;
class SimpleServerCoroutine
{
private Server $httpServer;
public function __construct($host, $port, $ssl = false)
{
$this->httpServer = new Server($host, $port, $ssl);
}
public function router(array $method, $path, $callback)
{
$this->httpServer->handle($path, function (Request $request, Response $response) use ($method, $callback) {
$m = $request->getMethod();
foreach ($method as $k => $v) {
$method[$k] = strtolower($v);
}
$m = strtolower($m);
if (!in_array($m, $method)) {
$response->status(405);
$data = [
'code' => 405,
'msg' => 'Method Not Allowed',
'currentMethod' => $m,
'allowMethod' => $method,
];
$response->end(json_encode($data));
return;
}
$requestInfo = [
'method' => $request->getMethod(),
'path' => $request->server['path_info'],
'uri' => $request->server['request_uri'],
'get' => $request->get ?: [],
'post' => $request->post ?: [],
'header' => $request->header ?: [],
'cookie' => $request->cookie ?: [],
'rawContent' => $request->rawContent() ?: ''
];
output($requestInfo['method'], $requestInfo['path'], "GET:" . json_encode($requestInfo['get']), "POST:" . json_encode($requestInfo['post']), "rawContent:" . $requestInfo['rawContent']);
$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();
}
public function stop()
{
$this->httpServer->shutdown();
}
}