Skip to content

Instantly share code, notes, and snippets.

@cursedcoder
Created March 31, 2018 06:14
Show Gist options
  • Save cursedcoder/7758ed6c689e62976474435db988dabc to your computer and use it in GitHub Desktop.
Save cursedcoder/7758ed6c689e62976474435db988dabc to your computer and use it in GitHub Desktop.
Compare express.js with amphp/http-server
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Running on port 3000.');
});
<?php
require __DIR__ . '/vendor/autoload.php';
use Amp\ByteStream\ResourceOutputStream;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestHandler\CallableRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Server;
use Amp\Http\Status;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Amp\Socket;
use Monolog\Logger;
// Run this script, then visit http://localhost:3000/ in your browser.
Amp\Loop::run(function () {
$servers = [
Socket\listen("0.0.0.0:3000"),
Socket\listen("[::]:3000"),
];
$server = new Server($servers, new CallableRequestHandler(function (Request $request) {
return new Response(Status::OK, [
"content-type" => "text/plain; charset=utf-8"
], "Hello, World!");
}));
yield $server->start();
// Stop the server when SIGINT is received (this is technically optional, but it is best to call Server::stop()).
Amp\Loop::onSignal(SIGINT, function (string $watcherId) use ($server) {
Amp\Loop::cancel($watcherId);
yield $server->stop();
});
});
<?php
require __DIR__ . '/vendor/autoload.php';
use Amp\ByteStream\ResourceOutputStream;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestHandler\CallableRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Server;
use Amp\Http\Status;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Amp\Socket;
use Monolog\Logger;
// Run this script, then visit http://localhost:3000/ in your browser.
Amp\Loop::run(function () {
$servers = [
Socket\listen("0.0.0.0:3000"),
Socket\listen("[::]:3000"),
];
$logHandler = new StreamHandler(new ResourceOutputStream(\STDOUT));
$logHandler->setFormatter(new ConsoleFormatter);
$logger = new Logger('server');
$logger->pushHandler($logHandler);
$server = new Server($servers, new CallableRequestHandler(function (Request $request) {
return new Response(Status::OK, [
"content-type" => "text/plain; charset=utf-8"
], "Hello, World!");
}), $logger);
yield $server->start();
// Stop the server when SIGINT is received (this is technically optional, but it is best to call Server::stop()).
Amp\Loop::onSignal(SIGINT, function (string $watcherId) use ($server) {
Amp\Loop::cancel($watcherId);
yield $server->stop();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment