作者 karlet

feat:simpleServer

  1 +<?php
  2 +
  3 +namespace Jiaoyin;
  4 +
  5 +class SimpleRequest
  6 +{
  7 + public string $path;
  8 + public string $uri;
  9 + public array $get;
  10 + public array $post;
  11 + public string $method;
  12 + public array $header;
  13 + public array $cookie;
  14 +
  15 + public function __construct($data)
  16 + {
  17 + $this->path = $data['path_info'];
  18 + $this->uri = $data['uri'];
  19 + $this->get = $data['get'];
  20 + $this->post = $data['post'];
  21 + $this->method = $data['method'];
  22 + $this->header = $data['header'];
  23 + $this->cookie = $data['cookie'];
  24 + }
  25 +}
  1 +<?php
  2 +namespace Jiaoyin;
  3 +use Swoole\Http\Request;
  4 +use Swoole\Http\Response;
  5 +use Swoole\Http\Server;
  6 +
  7 +class SimpleServer
  8 +{
  9 + private Server $httpServer;
  10 + public function __construct($host, $port)
  11 + {
  12 + $this->httpServer = new Server($host, $port);
  13 + }
  14 + public function router($url, $callback){
  15 + $this->httpServer->on($url, function ($request, $response) use ($callback){
  16 + $response->header("Content-Type", "text/plain");
  17 + $content = call_user_func($callback);
  18 + $response->end("Hello World\n");
  19 + });
  20 + $this->httpServer->on('Request', function (Request $request, Response $response) use ($url, $callback){
  21 + $requestInfo = [
  22 + 'path' => $request->server['path_info'],
  23 + 'uri' => $request->server['request_uri'],
  24 + 'get' => $request->get,
  25 + 'post' => $request->post,
  26 + 'method' => $request->getMethod(),
  27 + 'header' => $request->header,
  28 + 'cookie' => $request->cookie,
  29 + ];
  30 + $simpleRequest = new SimpleRequest($requestInfo);
  31 + if ($simpleRequest->path == '/favicon.ico' || $simpleRequest->uri == '/favicon.ico') {
  32 + $response->end();
  33 + return;
  34 + }
  35 + if($url == $simpleRequest->uri){
  36 + $res = call_user_func($callback, $simpleRequest);
  37 + if(!$res){
  38 + $response->end();
  39 + }else{
  40 + $response->end($res);
  41 + }
  42 + return;
  43 + }
  44 + $response->end("<h3>Hello Simple Server</h3>");
  45 + });
  46 + }
  47 +
  48 + public function start(){
  49 + $this->httpServer->start();
  50 + }
  51 +}
  52 +