Koa - HelloWorld

以上便是全部了,我们重点来看示例,我们只注册一个中间件, Hello Worler Server:

  1. <?php
  2. $app = new Application();
  3. // ...
  4. $app->υse(function(Context $ctx) {
  5. $ctx->status = 200;
  6. $ctx->body = "<h1>Hello World</h1>";
  7. });
  8. $app->listen(3000);

我们在Hello中间件前面注册一个Reponse-Time中间件,注意看,我们的逻辑是连贯的:

  1. <?php
  2. $app->υse(function(Context $ctx, $next) {
  3. $start = microtime(true);
  4. yield $next; // 执行后续中间件
  5. $ms = number_format(microtime(true) - $start, 7);
  6. // response header 写入 X-Response-Time: xxxms
  7. $ctx->{"X-Response-Time"} = "{$ms}ms";
  8. });