Git Product home page Git Product logo

http-server-router's Introduction

http-server-router

AMPHP is a collection of event-driven libraries for PHP designed with fibers and concurrency in mind. This package provides a routing RequestHandler for amphp/http-server based on the request path and method using FastRoute.

Installation

This package can be installed as a Composer dependency. You should specify amphp/http-server as a separate dependency.

composer require amphp/http-server-router

Usage

Router implements RequestHandler, which is used by an HttpServer to handle incoming requests. Incoming requests are routed by Router to other RequestHandlers based on the request path.

Routes can be defined using the addRoute($method, $uri, $requestHandler) method.

public function addRoute(
    string $method,
    string $uri,
    RequestHandler $requestHandler
): void

Matched route arguments are available in the request attributes under the Amp\Http\Server\Router key as an associative array. Please read the FastRoute documentation on how to define placeholders.

Middleware

You can stack all routes with a common set of middleware using addMiddleware($middleware). Each middleware is called in the order of the addMiddleware() calls. The router will not invoke any middleware for the fallback handler.

public function addMiddleware(Middleware $middleware): void

Note Per-route middleware can be added by using Amp\Http\Server\Middleware\stackMiddleware() before passing the RequestHandler to addRoute().

Fallback

If no routes match a request path, you can specify another instance of RequestHandler which will handle any unmatched routes. If no fallback handler is provided, a 404 response will be returned using the instance of ErrorHandler provided to the Router constructor.

public function setFallback(RequestHandler $requestHandler): void

Note Middleware defined by Router::addMiddleware() will not be invoked when a request is forwarded to fallback handler. Use Amp\Http\Server\Middleware\stackMiddleware() to wrap the fallback request handler with any middlewares needed first.

Example

use Amp\Http\HttpStatus;
use Amp\Http\Server\DefaultErrorHandler;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Router;
use Amp\Http\Server\SocketHttpServer;

// $logger is an instance of a PSR-3 logger.
$server = SocketHttpServer::createForDirectAccess($logger);
$errorHandler = new DefaultErrorHandler();

$router = new Router($server, $logger, $errorHandler);

$router->addRoute('GET', '/', new ClosureRequestHandler(
    function () {
        return new Response(
            status: HttpStatus::OK,
            headers: ['content-type' => 'text/plain'],
            body: 'Hello, world!',
        );
    },
));

$router->addRoute('GET', '/{name}', new ClosureRequestHandler(
    function (Request $request) {
        $args = $request->getAttribute(Router::class);
        return new Response(
            status: HttpStatus::OK,
            headers: ['content-type' => 'text/plain'],
            body: "Hello, {$args['name']}!",
        );
    },
));

$server->expose('0.0.0.0:1337');

$server->start($router, $errorHandler);

// Serve requests until SIGINT or SIGTERM is received by the process.
Amp\trapSignal([SIGINT, SIGTERM]);

$server->stop();

A full example is found in examples/hello-world.php.

php examples/hello-world.php

Limitations

The Router will decode the URI path before matching. This will also decode any forward slashes (/), which might result in unexpected matching for URIs with encoded slashes. FastRoute placeholders match path segments by default, which are separated by slashes. That means a route like /token/{token} won't match if the token contains an encoded slash. You can work around this limitation by using a custom regular expression for the placeholder like /token/{token:.+}.

Security

If you discover any security related issues, please use the private security issue reporter instead of using the public issue tracker.

License

The MIT License (MIT). Please see LICENSE for more information.

http-server-router's People

Contributors

bosunski avatar kelunik avatar thgs avatar trowski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-server-router's Issues

Allow server to start with only fallback defined

Currently the server refuses to start when there are no explicit routes defined.

However when having no explicit routes, but having a fallback defined the server should just start anyway:

$router = new Router();

$router->setFallback($this->auryn->make(FrontController::class));

$server = new Server($this->getServerSockets(), $router, $logger);

yield $server->start();

[2019-10-17T12:10:48.499397+00:00] HttpServer.info: Starting HTTP server
[2019-10-17T12:10:49.525568+00:00] HttpServer.critical: Could not start server
[2019-10-17T12:10:49.526294+00:00] HttpServer.error: Router start failure: no routes registered

Which is the best way to handle CORS preflight request with OPTIONS method?

I am creating a small API with Amphp Server in a subdomain and the interface is in the main domain, the classic usage is:

frontend
https://app.com

API
https://api.app.com

The browser is sending a preflight request, GET + preflight, with the OPTIONS method, so the server responds NOT ALLOWED METHOD and the browser returns a CORS error.

I could send the pull request but before sending it I'm researching the best way to do it. Please, check the following PR #13 for a better context.

The idea in this code is handle CORS preflight request using a global middleware, so the question is: ¿Is it the best way? ¿could I send a pull request with an improved code but with same idea?. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.