innmind/async-http-server

3.0.1 2024-08-03 14:48 UTC

This package is auto-updated.

Last update: 2024-09-03 15:08:30 UTC


README

Build Status Type Coverage

基于 Fiber 的实验性异步 HTTP 服务器。

安装

composer require innmind/async-http-server

使用

# server.php
<?php
declare(strict_types=1);

require 'path/to/vendor/autoload.php';

use Innmind\Async\HttpServer\Main;
use Innmind\OperatingSystem\OperatingSystem;
use Innmind\Http\{
    ServerRequest,
    Response,
    Response\StatusCode,
};
use Innmind\Filesystem\Name;
use Innmind\Url\Path;

new class extends Main {
    protected static function handle(ServerRequest $request, OperatingSystem $os): Response
    {
        return $os
            ->filesystem()
            ->mount(Path::of('somewhere/'))
            ->get(Name::of('some-file'))
            ->match(
                static fn($file) => Response::of(
                    StatusCode::ok,
                    $request->protocolVersion(),
                    null,
                    $file->content(),
                ),
                static fn() => Response::of(
                    StatusCode::notFound,
                    $request->protocolVersion(),
                ),
            );
    }
};

您可以通过命令 php server.php 运行此服务器。默认情况下,服务器在端口 8080 上公开。

此示例将返回文件系统上存在的 somewhere/some-file 文件的内容,如果不存在则返回 404 not found

此程序的非同步性由 OperatingSystem 抽象处理,这意味着您可以编写仿佛它是同步的代码。

注意

您可以通过 php server.php --help 运行命令来查看可配置服务器的选项。