swoole-server-noasync.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. require_once __DIR__.'/db-no-async.php';
  3. use Swoole\Http\Request;
  4. use Swoole\Http\Response;
  5. $server = new swoole_http_server('0.0.0.0', 8080, SWOOLE_BASE);
  6. $server->set([
  7. 'worker_num' => swoole_cpu_num() * 4,
  8. 'log_file' => '/dev/null',
  9. 'log_level' => 5,
  10. ]);
  11. /**
  12. * On start of the PHP worker. One worker per server process is started.
  13. */
  14. $server->on('workerStart', function () {
  15. Db::init();
  16. });
  17. /**
  18. * On every request to the (web)server, execute the following code
  19. */
  20. $server->on('request', static function (Request $req, Response $res) {
  21. try {
  22. switch ($req->server['request_uri']) {
  23. case '/json':
  24. $res->header('Content-Type', 'application/json');
  25. $res->end(json_encode(['message' => 'Hello, World!']));
  26. break;
  27. case '/plaintext':
  28. $res->header('Content-Type', 'text/plain; charset=utf-8');
  29. $res->end('Hello, World!');
  30. break;
  31. case '/db':
  32. $res->header('Content-Type', 'application/json');
  33. $res->end(db());
  34. break;
  35. case '/query':
  36. $res->header('Content-Type', 'application/json');
  37. $res->end(query((int) $req->get['q'] ?? 1));
  38. break;
  39. case '/fortunes':
  40. $res->header('Content-Type', 'text/html; charset=utf-8');
  41. $res->end(fortunes());
  42. break;
  43. case '/updates':
  44. $res->header('Content-Type', 'application/json');
  45. $res->end(updates((int) $req->get['q'] ?? 1));
  46. break;
  47. default:
  48. $res->status(404);
  49. $res->end('Not Found.');
  50. }
  51. } catch (\Throwable $e) {
  52. $res->status(500);
  53. $res->end('code ' . $e->getCode(). 'msg: '. $e->getMessage());
  54. }
  55. });
  56. $server->start();