swoole-server.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. require __DIR__.'/database.php';
  3. use Swoole\Http\Server;
  4. use Swoole\Http\Request;
  5. use Swoole\Http\Response;
  6. $enableCoroutine = getenv('ENABLE_COROUTINE') == 1;
  7. $connection = $enableCoroutine ? Connections::class : Connection::class;
  8. $setting = [
  9. 'worker_num' => swoole_cpu_num() * ((int) getenv('CPU_MULTIPLES')),
  10. 'log_file' => '/dev/null',
  11. 'enable_coroutine' => $enableCoroutine,
  12. 'enable_reuse_port' => true,
  13. 'http_compression' => false
  14. ];
  15. if ($enableCoroutine) {
  16. $setting['hook_flags'] = SWOOLE_HOOK_ALL;
  17. }
  18. $server = new Server('0.0.0.0', 8080);
  19. $server->set($setting);
  20. $server->on('workerStart', function () use ($connection) {
  21. $connection::init(getenv('DATABASE_DRIVER'));
  22. });
  23. $server->on('request', function (Request $req, Response $res) use ($connection) {
  24. try {
  25. switch ($req->server['request_uri']) {
  26. case '/plaintext':
  27. $res->header['Content-Type'] = 'text/plain; charset=utf-8';
  28. $res->end('Hello, World!');
  29. break;
  30. case '/json':
  31. $res->header['Content-Type'] = 'application/json';
  32. $res->end(json_encode(['message' => 'Hello, World!']));
  33. break;
  34. case '/db':
  35. $res->header['Content-Type'] = ['application/json'];
  36. $res->end($connection::db());
  37. break;
  38. case '/fortunes':
  39. $res->header['Content-Type'] = 'text/html; charset=utf-8';
  40. $res->end($connection::fortunes());
  41. break;
  42. case '/query':
  43. $queries = isset($req->get['queries']) ? (int) $req->get['queries'] : -1;
  44. $query_count = $queries > 1 ? min($queries, 500) : 1;
  45. $res->header['Content-Type'] = 'application/json';
  46. $res->end($connection::query($query_count));
  47. break;
  48. case '/updates':
  49. $queries = isset($req->get['queries']) ? (int) $req->get['queries'] : -1;
  50. $query_count = $queries > 1 ? min($queries, 500) : 1;
  51. $res->header['Content-Type'] = 'application/json';
  52. $res->end($connection::updates($query_count));
  53. break;
  54. default:
  55. $res->status(404);
  56. $res->end('Error 404');
  57. }
  58. } catch (Throwable) {
  59. $res->status(500);
  60. $res->end('Error 500');
  61. }
  62. });
  63. $server->start();