作者 karlet

feat:simpleServer

<?php
namespace Jiaoyin;
class SimpleRequest
{
public string $path;
public string $uri;
public array $get;
public array $post;
public string $method;
public array $header;
public array $cookie;
public function __construct($data)
{
$this->path = $data['path_info'];
$this->uri = $data['uri'];
$this->get = $data['get'];
$this->post = $data['post'];
$this->method = $data['method'];
$this->header = $data['header'];
$this->cookie = $data['cookie'];
}
}
\ No newline at end of file
... ...
<?php
namespace Jiaoyin;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
class SimpleServer
{
private Server $httpServer;
public function __construct($host, $port)
{
$this->httpServer = new Server($host, $port);
}
public function router($url, $callback){
$this->httpServer->on($url, function ($request, $response) use ($callback){
$response->header("Content-Type", "text/plain");
$content = call_user_func($callback);
$response->end("Hello World\n");
});
$this->httpServer->on('Request', function (Request $request, Response $response) use ($url, $callback){
$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);
if ($simpleRequest->path == '/favicon.ico' || $simpleRequest->uri == '/favicon.ico') {
$response->end();
return;
}
if($url == $simpleRequest->uri){
$res = call_user_func($callback, $simpleRequest);
if(!$res){
$response->end();
}else{
$response->end($res);
}
return;
}
$response->end("<h3>Hello Simple Server</h3>");
});
}
public function start(){
$this->httpServer->start();
}
}
... ...