使用Swoole可通过HTTP服务器结合路径解析与请求方法判断实现RESTful API,支持GET、POST、PUT、DELETE等操作,通过路由匹配处理用户资源的增删改查,并返回JSON响应,具备高性能优势。使用 Swoole 实现一个支持 RESTful 风格的 API 服务,核心在于利用 Swoole 的 HTTP 服务器能力,并结合路由解析、请求方法判断和响应处理来模拟传统 Web 框架中的 REST 路由机制。 Swoole 本身不内置路由系统,但可以通过手动解析请求路径与请求方法(GET、POST、PUT、DELETE 等)来实现标准的 RESTful 接口。下面是一个简洁清晰的实现方式。
首先启动一个 Swoole HTTP 服务器,监听指定端口:
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('start', function ($server) {
echo "HTTP Server is started at http://0.0.0.0:9501\n";
});
在 request 回调中,根据请求的路径和方法进行分发:
$http->on('request', function ($request, $response)
{
$path = parse_url($request->server['request_uri'], PHP_URL_PATH);
$method = $request->server['request_method'];
// 设置通用响应头
$response->header('Content-Type', 'application/json');
// 模拟用户资源路由
if ($path === '/api/users' && $method === 'GET') {
$response->end(json_encode([
'code' => 0,
'data' => [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']]
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'GET') {
$userId = $matches[1];
$response->end(json_encode([
'code' => 0,
'data' => ['id' => $userId, 'name' => 'User' . $userId]
]));
} elseif ($path === '/api/users' && $method === 'POST') {
$data = json_decode($request->rawContent(), true);
$response->status(201);
$response->end(json_encode([
'code' => 0,
'message' => 'User created',
'data' => $data
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'PUT') {
$userId = $matches[1];
$data = json_decode($request->rawContent(), true);
$response->end(json_encode([
'code' => 0,
'message' => "User {$userId} updated",
'data' => $data
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'DELETE') {
$userId = $matches[1];
$response->end(json_encode([
'code' => 0,
'message' => "User {$userId} deleted"
]));
} else {
$response->status(404);
$response->end(json_encode(['code' => 404, 'message' => 'Not Found']));
}
});
添加最后的启动命令:
$http->start();
保存为 server.php,运行:php server.php
即可通过以下方式测试:
实际项目中可进一步优化: