http

Router, requests and responses, and a small HTTP server.

v1.0.0Web & networkingbundledimport "http";
Overview Installation Documentation Examples

Overview

HTTP/1.1 for HolyPHP: parse requests, build responses, route /users/{id} to handlers and serve them on the async event loop. Handlers are plain functions from a request to a response, so the whole app can be tested without opening a socket.

bundled — works offline router with {params} JSON, HTML, text, redirects 404 / 405 / 500 built in testable without sockets

Quick start

import "http";

$app = new HttpRouter();
$app->get("/", function(HttpRequest $req): HttpResponse {
    return http_html("<h1>Hello</h1>");
});
$app->get("/users/{id}", function(HttpRequest $req): HttpResponse {
    return http_json(["id" => intval($req->param("id"))]);
});
http_serve($app, "tcp://127.0.0.1:8080");
$ curl http://127.0.0.1:8080/users/42
{"id":42}

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install http

This adds the library to hphp.yaml, installs it into .hphp/packages/http/ and pins the exact version in hphp.lock:

require:
  http: "^1.0"

It needs async; hphp install adds it automatically.

Use it

import "http";

http is bundled with the compiler, so import "http"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install http          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install http
Packagehttp
Version1.0.0 (follows the compiler)
Entry filehttp.hphp
Sourcepackages/lib/http ↗

Documentation

Routing

Add routes with get, post, put, patch, delete or any; each returns the router, so calls chain. Routes are tried in the order they were added.

PatternMatches$req->params
/users/users, /users/[]
/users/{id}/users/7["id" => "7"]
/users/{id}/posts/{p}/users/7/posts/3["id" => "7", "p" => "3"]
/files/*/files/a/b.txt["*" => "a/b.txt"]

No match gives 404 (or your notFound() handler), a path that exists only for another method gives 405, and a handler that throws gives 500 with the message. HEAD requests use the GET route and send no body.

HttpRequest

MemberWhat it is
$method, $path, $query, $target, $versionthe request line ($path is URL-decoded)
$headerslowercase name → value
$bodythe body, cut to Content-Length
header($name, $default)a header, any case
param($name, $default)a route placeholder
input($name, $default)a query parameter or a field of a urlencoded form
json()the body decoded as JSON

HttpResponse

HelperResponse
http_text($body, $status = 200)text/plain
http_html($body, $status = 200)text/html
http_json($data, $status = 200)application/json, encoded with json_encode
http_redirect($url, $status = 302)sets Location
http_not_found($message)404
new HttpResponse($status, $body, $type)anything else; ->header($name, $value) chains

$response->toString() is the raw HTTP text including Content-Length.

Without sockets

FunctionWhat it does
http_parse($raw)raw request text → HttpRequest
http_complete($raw)true when headers and the Content-Length body have arrived
$router->dispatch($req)request → response
$router->handle($raw)raw request text → raw response text
http_parse_query("a=1&b=2")URL-decoded map
http_match("/u/{id}", "/u/7")the params, or null

Serving

http_serve($router, "tcp://127.0.0.1:8080", $log = true) runs one event loop, buffers each request until it is complete (large bodies arrive in several chunks), answers with Connection: close and prints one line per request when $log is true. To combine it with timers or WebSockets, take its body as a template and add your own watchers to the same Loop.

Examples

5 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01Hello, web

The smallest useful server: one route that answers with HTML. Start it, open the address in a browser, and stop it with Ctrl-C.

01-hello-server.hphp
<?php
import "http";

$app = new HttpRouter();

// GET / answers with a small HTML page
$app->get("/", function(HttpRequest $req): HttpResponse {
    return http_html("<h1>Hello from HolyPHP</h1>");
});

// serve until the program is stopped
http_serve($app, "tcp://127.0.0.1:8080");
Try it
hphp run 01-hello-server.hphp
curl http://127.0.0.1:8080/

02A JSON API with route parameters

A read-only API over a list of books. {id} in a route becomes $req->param("id"), query strings are read with $req->input(), and http_json() turns any array into a JSON response.

02-json-api.hphp
<?php
import "http";

$books = [
    ["id" => 0, "title" => "The Dispossessed", "author" => "Ursula K. Le Guin"],
    ["id" => 1, "title" => "A Wizard of Earthsea", "author" => "Ursula K. Le Guin"],
    ["id" => 2, "title" => "Solaris", "author" => "Stanislaw Lem"],
];

$app = new HttpRouter();

// all books, optionally filtered by ?author=
$app->get("/books", function(HttpRequest $req) use ($books): HttpResponse {
    $author = $req->input("author");
    $found = [];

    foreach ($books as $book) {
        if ($author == "" || $book["author"] == $author) {
            $found[] = $book;
        }
    }

    return http_json(["count" => count($found), "books" => $found]);
});

// one book by its id, or a JSON error with status 404
$app->get("/books/{id}", function(HttpRequest $req) use ($books): HttpResponse {
    $id = intval($req->param("id"));

    if ($id < 0 || $id >= count($books)) {
        return http_json(["error" => "no book with id " . $id], 404);
    }

    return http_json($books[$id]);
});

http_serve($app, "tcp://127.0.0.1:8080");
Try it
hphp run 02-json-api.hphp
curl http://127.0.0.1:8080/books
curl "http://127.0.0.1:8080/books?author=Ursula%20K.%20Le%20Guin"
curl http://127.0.0.1:8080/books/1

03A guestbook: forms, POST and redirects

GET / shows the entries and a form. The form posts to /sign, which reads the fields with $req->input() and redirects back with http_redirect() (the classic POST/redirect/GET pattern). The entries live in memory, shared through a by-reference capture.

03-form-and-redirect.hphp
<?php
import "http";

$entries = [];

// escape user input before putting it into HTML
function html_text(string $s): string {
    return htmlspecialchars($s);
}

$app = new HttpRouter();

// the page: the form and every entry so far
$app->get("/", function(HttpRequest $req) use (&$entries): HttpResponse {
    $html = "<h1>Guestbook</h1>";
    $html = $html . "<form method='post' action='/sign'>";
    $html = $html . "<input name='name' placeholder='Your name'> ";
    $html = $html . "<input name='message' placeholder='Message'> ";
    $html = $html . "<button>Sign</button></form><ul>";

    foreach ($entries as $entry) {
        $html = $html . "<li><b>" . html_text($entry[0]) . "</b>: " . html_text($entry[1]) . "</li>";
    }

    return http_html($html . "</ul>");
});

// the form target: store the entry, then go back to the page
$app->post("/sign", function(HttpRequest $req) use (&$entries): HttpResponse {
    $name = trim($req->input("name"));
    $message = trim($req->input("message"));

    if ($name == "" || $message == "") {
        return http_text("name and message are required", 422);
    }

    $entries[] = [$name, $message];
    return http_redirect("/", 303);
});

http_serve($app, "tcp://127.0.0.1:8080");
Try it
hphp run 03-form-and-redirect.hphp
open http://127.0.0.1:8080/ in a browser

04Testing routes without a server

Routers do not need sockets: build the app in a function, then call dispatch() with requests made by http_parse(). This is how an app's tests look in a project (put it in tests/ and run hphp test).

04-test-routes.hphp
<?php
import "http";
import "testing";

// the app, as it would live in src/app.hphp
function make_app(): HttpRouter {
    $app = new HttpRouter();

    $app->get("/hello/{name}", function(HttpRequest $req): HttpResponse {
        return http_text("Hello, " . $req->param("name") . "!");
    });

    $app->post("/sum", function(HttpRequest $req): HttpResponse {
        $a = intval($req->input("a"));
        $b = intval($req->input("b"));
        return http_json(["sum" => $a + $b]);
    });

    return $app;
}

// a raw request, as a browser would send it
function get_request(string $path): HttpRequest {
    return http_parse("GET " . $path . " HTTP/1.1\r\nHost: test\r\n\r\n");
}

$app = make_app();
$t = new Test("routes");

$t->section("GET /hello/{name}");
$res = $app->dispatch(get_request("/hello/Ada"));
$t->equal($res->status, 200, "status 200");
$t->equal($res->body, "Hello, Ada!", "greets by name");

$t->section("POST /sum");
$form = "a=2&b=40";
$post = http_parse("POST /sum HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: "
    . strlen($form) . "\r\n\r\n" . $form);
$t->equal($app->dispatch($post)->body, "{\"sum\":42}", "adds the fields");

$t->section("errors");
$t->equal($app->dispatch(get_request("/nope"))->status, 404, "unknown path is 404");
$t->equal($app->dispatch(get_request("/sum"))->status, 405, "wrong method is 405");

$t->done();
Try it
hphp run 04-test-routes.hphp

05A configurable service with a health check

Reads its port and name from the environment with the dotenv library, answers /health for load balancers, and wraps every handler in timed() so each request is logged with its duration.

05-config-and-logging.hphp
<?php
import "http";
import "dotenv";

env_load();
$port = env_int("PORT", 8080);
$service = env("SERVICE_NAME", "demo-service");
$started = time();

// wrap a handler: same response, plus one log line with the duration
function timed($handler) {
    return function(HttpRequest $req) use ($handler): HttpResponse {
        $start = hrtime(true);
        $res = $handler($req) as HttpResponse;
        $ms = intval((hrtime(true) - $start) / 1000000);
        echo $req->method . " " . $req->path . " -> " . $res->status . " (" . $ms . " ms)";
        return $res;
    };
}

$app = new HttpRouter();

$app->get("/health", timed(function(HttpRequest $req) use ($service, $started): HttpResponse {
    return http_json([
        "status" => "ok",
        "service" => $service,
        "uptime_seconds" => time() - $started,
    ]);
}));

$app->get("/", timed(function(HttpRequest $req) use ($service): HttpResponse {
    return http_text($service . " is running. Try /health.");
}));

// logging is done by timed(), so the server's own log is off
http_serve($app, "tcp://127.0.0.1:" . $port, false);
Try it
PORT=9090 hphp run 05-config-and-logging.hphp
curl http://127.0.0.1:9090/health