-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.php
More file actions
69 lines (56 loc) · 1.87 KB
/
app.php
File metadata and controls
69 lines (56 loc) · 1.87 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
68
69
<?php
use Swoole\Http\Server;
use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
use Controllers\Http\Response;
use Controllers\Http\Request;
use Data\Log;
use Data\Cache;
use Data\SessionManager;
$PORT = 8080;
$server = new Server("localhost", $PORT);
$server->set([
'reload_async' => true, // hot reload
'worker_num' => 4,
'enable_coroutine' => true,
'log_file' => __DIR__ . '/data/logs/swoole.log',
// 'daemonize' => true
]);
$cache = Cache::getInstance();
$server->on("start", function ($server) {
error_log("Swoole HTTP server is started on localhost\n");
});
$server->on("request", function (SwooleRequest $request, SwooleResponse $response) use ($router) {
SessionManager::start();
$uri = $request->server['request_uri'];
// cast request and response to our classes
$request = new Request($request);
$response = new Response($response);
// handling static files.
// todo: find a way to serve these files without parsing through router.
if (strpos($uri, "/static") === 0 || $uri === "/favicon.ico") {
// If the request is for a static file, read the file and send it as the response
$filepath = __DIR__ . $uri;
if (is_file($filepath) && file_exists($filepath)) {
$mime = Controllers\Utils\Helpers\get_mime_type($filepath);
$response->swoole->header('Content-Type', $mime);
$response->swoole->end(file_get_contents($filepath));
return;
}
}
if (!$router) return;
if (!$router->resolve($request, $response)) {
$response->swoole->status(404);
$response->swoole->end("Not found");
}
});
$server->on("WorkerStart", function ($server, $worker_id) {
// Remove this if you don't want to use the queue
if ($worker_id === 0) {
swoole_timer_tick(10000, function() { // process every 10 seconds
Controllers\Utils\Queue::work();
(Cache::getInstance())->manage(); // delete expired cache keys
});
}
});
$server->start();