-
-
Save nezamy/53512b03a2460a44a097abb01cc61240 to your computer and use it in GitHub Desktop.
Swoole HTTP static file server example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Simple HTTP static file server using Swoole | |
$host = $argv[1] ?? '127.0.0.1'; | |
$port = $argv[2] ?? 9501; | |
$http = new swoole_http_server($host, $port); | |
// The usage of enable_static_handler seems to produce errors | |
// $http->set([ | |
// 'document_root' => __DIR__, | |
// 'enable_static_handler' => true | |
// ]); | |
$http->on("start", function ($server) { | |
printf("HTTP server started at %s:%s\n", $server->host, $server->port); | |
printf("Master PID: %d\n", $server->master_pid); | |
printf("Manager PID: %d\n", $server->manager_pid); | |
}); | |
$static = [ | |
'css' => 'text/css', | |
'js' => 'text/javascript', | |
'png' => 'image/png', | |
'gif' => 'image/gif', | |
'jpg' => 'image/jpg', | |
'jpeg' => 'image/jpg', | |
'mp4' => 'video/mp4' | |
]; | |
$http->on("request", function ($request, $response) use ($static) { | |
if (getStaticFile($request, $response, $static)) { | |
return; | |
} | |
$response->status(404); | |
$response->end(); | |
}); | |
$http->start(); | |
function getStaticFile( | |
swoole_http_request $request, | |
swoole_http_response $response, | |
array $static | |
) : bool { | |
$staticFile = __DIR__ . $request->server['request_uri']; | |
if (! file_exists($staticFile)) { | |
return false; | |
} | |
$type = pathinfo($staticFile, PATHINFO_EXTENSION); | |
if (! isset($static[$type])) { | |
return false; | |
} | |
$response->header('Content-Type', $static[$type]); | |
$response->sendfile($staticFile); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment