Skip to content
thesis-phpPublic

Latest commit

 

History

60 Commits

Folders and files

Repository files navigation

Thesis HTTP

PHP Release License PHPStan Coverage Mutation score

This read-only repository mirrors packages/http. Open issues and pull requests in the thesis-php/thesis monorepo.

Report a bug · Request a feature · Changelog · Contributing

Install with composer require thesis/http on 64-bit PHP 8.6+.

The client and server share messages and the same HTTP/1 implementation.

Messages

Clients and servers use the same Request and Response. Both extend Message, the public type for working with the headers and body of either one. Use with… methods to derive a message with different metadata. The original and its copies share one right to take the body.

use Thesis\Http\Request;
use Thesis\Http\Response;

$request = new Request('GET', 'https://example.org/search')
    ->withQueryParameter('tag', ['php', 'http'])
    ->withHeader('Accept', 'application/json');

$response = (new Response(body: 'ok'))->withAddedHeader('Set-Cookie', 'theme=dark');
$body = $response->takeBody();
$bytes = $body->readAll();
$trailers = $body->trailers();

Pass a URI string or a URI object to the request constructor or withUri(). withQuery() replaces the whole query. Pass an encoded string without the leading question mark, a Query, or an array of non-empty decoded names and their values. A list of values repeats the name. withAddedQuery() accepts the same inputs and appends pairs, preserving the original encoded query. Use withAddedQueryParameter() to append values for one name. withoutQueryParameter() removes every occurrence of the name.

Message constructors, withHeaders() and StringBody trailers accept a Headers object or an array mapping each field name to a string or list of strings.

Requests and responses default to Thesis\Http\EMPTY_BODY, a reusable empty body with empty trailers. Pass a string or an unread body to supply a payload. Give the message exclusive access until takeBody() transfers the reader to its caller. Dropping the last message copy closes an unclaimed body. A second call through any metadata copy raises LogicException. A proxy can pass $request->withUri($upstream) to the client and return its response directly. Taking either body also transfers its trailers. Use withBody() to supply a replacement.

Use $body->discard() to consume the remaining bytes and return the final trailer fields, even after a partial read. Read incrementally or call readAll() for the whole payload (8 MiB by default). Pass limit: to choose a byte limit. Overflow and read failures close the body. After any bytes have been consumed, collecting the whole body raises LogicException. Close the reader to release its resources. Supply ready trailer fields with new StringBody($bytes, $trailers). A streaming body can determine its fields while reading. Calling trailers() while fields are still pending raises LogicException.

Use Response::json($value, status: Status::CREATED) to encode a PHP value as application/json. Use Response::html($body) for a UTF-8 HTML string or stream. For a local file, use Response::html(new FileBody($path)) with Thesis\Http\FileBody. The body opens the file and gets its size from the same handle. Both constructors default to status 200. Use withAddedHeaders() to append field lines to the response, or withHeader() to replace its Content-Type.

$value = $request->takeJson(associative: false, limit: 64 * 1024);
return Response::json($value);

Use $request->withJson($value) or $response->withJson($value) to copy a message with a new JSON body and set its Content-Type to application/json. Pass encoding options as flags: and the maximum nesting level as depth: (default 512). Encoding failures throw JsonException unless JSON_PARTIAL_OUTPUT_ON_ERROR requests partial output.

On requests and responses, takeJson() takes the body once, even when decoding fails. It uses the same default limit as readAll(). If you need trailers, use takeBody(), read the body to the end, then call trailers() on it. JSON objects decode to associative arrays by default. Pass associative: false for stdClass. takeJson() adds JSON_THROW_ON_ERROR to the supplied flags, so decoding failures throw JsonException.

A client middleware that may resend an upload takes the body before calling the next handler. It passes $request->withBody($body) on the first attempt. When policy permits another attempt and the body implements ReplayableBody, it passes $request->withBody($body->fresh()). This creates a new handoff with its own reader and trailers. StringBody supports replay. Headers, methods, status codes and ordered query parameters are shared by requests and responses.

Headers

Headers is immutable. It treats names as case-insensitive and can store several lines under the same name.

$headers = new Headers([
    'Accept' => ['text/html', 'application/json;q=0.9'],
    'User-Agent' => 'thesis',
]);

$headers->has('accept');          // true
$headers->get('ACCEPT');          // 'text/html, application/json;q=0.9'
$headers->all('accept');          // ['text/html', 'application/json;q=0.9']
$headers->get('cookie');          // null

$headers = $headers
    ->with('accept', 'text/plain')           // replaces the lines of the field
    ->withAdded('set-cookie', 'a=1')         // adds a line
    ->withAdded('set-cookie', 'b=2')
    ->without('user-agent');

foreach ($headers as $name => $lines) {
    // 'accept' => ['text/plain'], 'set-cookie' => ['a=1', 'b=2']
}
  • Names are stored in lowercase, as HTTP/2 requires.
  • get() joins the lines of a field with a comma, as RFC 9110 defines. set-cookie is the exception: its lines cannot be joined, use all().
  • Headers throws \ValueError if a name is invalid or a value contains a forbidden control character. So user input with \r\n in it cannot add a line to a message (response splitting). Spaces and tabs around a value are trimmed.

Client

A URL string sends a GET. Reuse the client across calls. Wrap both the request and the read in an async timeout to apply one deadline to connection acquisition, redirects and downloading the body.

use Thesis\Http\Client;
use function Thesis\Async\timeout;
use function Thesis\Time\sec;

$client = new Client();
$bytes = timeout(sec(10), static fn() => $client->send('https://example.com/')->takeBody()->readAll());

Send an HTTP/1.1 request inside a Thesis async scope. The final response head is available as soon as send() returns. Read the body under the deadline you want for the download. The client supplies a body that implements Closer. Close an unfinished body to close its connection immediately. A permanent read failure or dropping the last reference to an unfinished body also closes the connection. A malformed response head or body raises Thesis\Io\IoException during send() or while reading the body.

use Thesis\Http\Request;
use Thesis\Http\Client;
use Thesis\Http\Response;
use Uri\Rfc3986\Uri;
use function Thesis\Async\timeout;
use function Thesis\Time\sec;

$request = new Request('GET', new Uri('https://example.com/'));
$client = new Client();
$response = timeout(sec(5), static fn() => $client->send($request));
$status = $response->status;
$response->takeBody()->close();

Use withResponse() to close the body when a callback returns or throws:

$status = $client->withResponse('https://example.com/', static fn(Response $response) => $response->status);

Reuse the same client across requests to share connections for the same scheme, host and port. A fixed-length body releases its socket on the last byte. A chunked body releases it after the trailers. Take the body once, read until EOF to reuse the connection, then call $body->trailers() for the final fields. A bodyless response releases it immediately. The byte limit maxResponseHeadBytes covers informational and final response headers together (default 64 KiB). An outstanding body keeps its own socket and counts toward maxConnectionsPerOrigin (default 10). Further callers for that origin wait for a slot. The client retains up to maxIdleConnections sockets across all origins (default 32). Set it to zero to close each socket after its exchange. If a peer closes an idle connection, the next request opens a new one. A disconnect during a request propagates to the caller. Automatic retries are opt-in.

HTTPS verifies the peer through thesis/net. Pass a Net ClientTls configuration to the constructor to use a private CA. The transport takes and closes the request body before it reads the response. For another send, supply a new body with withBody() or build a new request.

Middleware

Pass middleware: [] for a single exchange with the original content encoding. By default the client runs FollowRedirects then DecodeContent. Supplying a list replaces the defaults. A middleware implements Thesis\Http\Client\Middleware with handle(Request $request, callable $next): Response. It can return a cached response, change the request using withHeader() or withBody(), call $next($request), or wrap the response body. Close intermediate responses before sending another request. Middleware before FollowRedirects sees the application request once. Middleware after it sees each destination. Scope credential injection to the intended origin.

FollowRedirects follows up to ten redirects. It resolves relative locations, turns a POST into a GET on 301/302, and drops the body on 303. For 307/308 it can resend a ReplayableBody with its original method. It returns the intermediate response when the body cannot be replayed, the limit is reached, the location is unusable, or HTTPS would downgrade to HTTP. Across origins only allowlisted negotiation and content headers carry over.

With ext-zlib installed, DecodeContent negotiates gzip and deflate, decompresses the stream as it is read, and preserves trailers. Set Accept-Encoding yourself or send a range request to keep control of the encoded bytes.

Place new RetryRequests(maxRetries: 1) last in the middleware list to retry an idempotent method with a ReplayableBody on a connection, read or write failure before the response arrives. It opens an independent reader on each retry. After send() returns, download errors propagate to the consumer.

A custom connector receives the origin host, port and optional ClientTls and returns a connected Thesis\Net\Socket. It runs only when the pool needs a new socket. Each client owns its pool.

Form uploads

Form::urlEncoded() builds a POST request. Use a list of values to repeat a name. Form::multipart() accepts ordered fields and files. Pass an unread Thesis\Io\Reader to upload a file or forward a stream. Construction only prepares the part headers. Sending the request reads the payload in chunks.

use Thesis\Http\Client\Form;
use Thesis\Http\Client\FormPart;

$request = Form::urlEncoded('https://example.com/search', ['tag' => ['news', 'science']]);
$upload = Form::multipart('https://example.com/files', [
    new FormPart('description', 'Monthly report'),
    new FormPart('file', $reader, filename: 'report.pdf', contentType: 'application/pdf'),
]);
$status = $client->withResponse($upload, static fn($response) => $response->status);

A string, an unread StringReader, or a Body of known size contributes its length automatically. For another reader, pass size: to send exactly that many bytes. An unknown length selects chunked transfer. Closing the multipart request body closes every part reader that implements Closer.

HTTP proxy

use Thesis\Http\Headers;
use Thesis\Http\Client;
use Thesis\Http\Client\HttpProxy;

$proxy = new HttpProxy('proxy.internal', 3128, new Headers(['Proxy-Authorization' => $proxyCredential]));
$response = (new Client(connector: $proxy))->send('https://example.com/');

The client connects to the proxy over plaintext HTTP and requests a CONNECT tunnel for the origin. If the proxy refuses CONNECT or returns a malformed response, opening the tunnel throws Thesis\Net\ConnectFailed. For HTTPS the client negotiates TLS inside the tunnel and verifies the origin's certificate.

Server

Serve HTTP/1 requests on one or more TCP or Unix listeners. Each connection runs in its own task. Requests on the same connection run in order. The handler receives the shared Thesis\Http\Request and a Thesis\Http\Server\Context with connection information. It returns a Thesis\Http\Response. Thesis\Http\Server defines two PHPStan types for this signature. The server constructor accepts Handler and stores the resulting closure as HandlerClosure. Import the latter with @phpstan-import-type HandlerClosure from \Thesis\Http\Server.

Routing

Build a Router once and pass it directly to Server. The constructor accepts an iterable of routes. Pass one method, a non-empty list of methods, or null to each Route. Named constructors such as Route::get() and Route::post() cover every method in Method. Use Route::any() for the fallback. Each route handler receives the request and the connection context. Inside the route handler and its middleware, Thesis\Http\Server\routeMatch($request) returns the active match. Use Thesis\Http\Server\routeParam($request, $name) to read one decoded parameter. It returns null when the parameter is absent or the request has no active match. Outside dispatch routeMatch() returns null. Read the selected method from $match->method and the registered pattern from $match->route->pattern. param($name) returns a decoded parameter or null, and $match->params contains all parameters.

use Thesis\Http\Response;
use Thesis\Http\Server\Config;
use Thesis\Http\Server\Route;
use Thesis\Http\Server\Router;
use Thesis\Http\Server;
use function Thesis\Http\Server\routeParam;

$router = new Router([
    Route::get('/users/me', static fn() => new Response(body: 'Current user')),
    Route::get('/users/{id}', static fn($request) => new Response(body: routeParam($request, 'id') ?? '')),
]);

$server = new Server(new Config(8080), $router);

Patterns start with a slash. A placeholder such as {user_id} consumes a nonempty segment. Names start with an ASCII letter or underscore and may also contain digits. Each name occurs once. Use trailing optional segments (/archive/{year?}/{month?}) or capture the remaining path with a final {path+} (nonempty) or {path*} (possibly empty). The remainder keeps its slashes. Omitted optional parameters are absent unless supplied in the route's defaults string map.

A segment can combine literals and parameters, for example /reports/{year}-{month}.csv. Pass PCRE fragments by parameter name in requirements, for example ['year' => '[0-9]{4}']. A requirement matches its parameter, including slashes for a remainder. The router tries literal, constrained or compound, ordinary parameter, then remainder at each position. Overlapping expressions at the same position are tried in registration order. An explicit endpoint precedes an omitted suffix. Duplicate method and path shapes fail during construction.

$router->list contains the original Route objects in registration order. A route with several methods appears once.

$router->match($request) selects a route without calling a handler or emitting an event. On success it returns a RouteMatch. Read the registered route from $match->route and the decoded parameters from $match->params. An invalid path returns RouteFailure::BadPath (400), an unknown path returns RouteFailure::NotFound (404), and a method mismatch returns MethodNotAllowed (405) with the list of method strings in $allowedMethods. Dispatch checks the method after selecting the complete path. An explicit HEAD wins over the GET fallback. A route with methods: null handles any remaining method for the selected path and reports the request's method in RouteMatch. Only one such route may occupy a path shape. For example, Route::any('/storage/{path+}', $proxy) forwards custom methods such as PROPFIND. A more specific path still owns its 405. A method mismatch yields 405 with Allow. Pass a default handler to serve unknown paths, for example new Router($routes, defaultHandler: $staticHandler). It receives the request and context. If omitted, the context's error handler handles the 404.

Matching uses the raw URI path. Dot segments, plus signs and trailing slashes keep their meaning. End a pattern with [/] to accept one optional slash. For example, /docs[/] matches both /docs and /docs/. A remainder must end its pattern and captures trailing slashes itself. An absolute URI with an empty path matches /. The special targets OPTIONS * and authority-form CONNECT have no route path. Percent escapes are decoded once. An invalid escape, an encoded slash or a NUL yields 400. For example, /users/a%252Fb passes a%2Fb to the handler.

By default, routing errors and server-generated 500 responses carry a small HTML page with the status code and its standard reason phrase when known. Pass an optional Server\ErrorHandler to the server to customize routing errors and 500 responses:

$errorHandler = new class implements \Thesis\Http\Server\ErrorHandler {
    public function handleError(int $status, \Thesis\Http\Request $request): \Thesis\Http\Response
    {
        return new \Thesis\Http\Response($status, body: "Request failed ($status)");
    }
};

$server = new Server(new Config(8080), new Router($routes), errorHandler: $errorHandler);

Return the supplied status. The router sets Allow on a 405. Protocol rejections still have an empty body. An explicit error response from an application handler passes through as returned.

Static files

StaticFiles looks up the decoded URI path relative to its directory. Pass it directly to the server to serve files at /, or register its route() under a URL prefix. GET returns the current file contents and HEAD returns the same media type and file length without reading the body. Directories, missing files and paths resolving outside the root return 404. GET streams the file in chunks and takes its length from the open file. Use a directory tree controlled by trusted writers, since path resolution and opening the file are separate operations.

use Thesis\Http\Server\StaticFiles;
use Thesis\Http\Server\Router;

$files = new StaticFiles(__DIR__ . '/public');
$router = new Router([$files->route('/static')]);

Streaming echo

use Thesis\Async\Group;
use Thesis\Http\Request;
use Thesis\Http\Response;
use Thesis\Http\Server\Config;
use Thesis\Http\Server;
use function Thesis\Async\awaitShutdownSignal;
use function Thesis\Async\group;

$server = new Server(
    config: new Config(8080),
    handler: static fn(Request $request) => new Response(
        body: $request->takeBody(),
    ),
);

group(static function (Group $group) use ($server) {
    $server->start($group);
    awaitShutdownSignal();
    $server->stop();
});

The response reads from the incoming body as it is written. A chunked request's trailers become available after its terminating chunk. The server reads them from the body and writes them in the last chunk of the response.

From the Thesis monorepo, run the example in Docker.

docker compose run --rm -p 127.0.0.1:8080:8080 php php packages/http/examples/echo.php

In another terminal, send two requests with one curl process. The first uses chunked transfer encoding. Curl prints the number of new connections it opened for the second request; expect zero.

curl --http1.1 -sS -H 'Transfer-Encoding: chunked' --data-binary 'one' http://127.0.0.1:8080/first \
  --next -sS --data-binary 'two' -w '\nnew connections: %{num_connects}\n' http://127.0.0.1:8080/second

Server middleware

Use Pipeline::wrap() to wrap a handler and pass it to the server. It collects the middleware from an iterable in iteration order, ignoring keys. An empty iterable returns the original handler. The same handler can serve concurrent requests.

use Thesis\Http\Server;
use Thesis\Http\Server\Pipeline;

$pipeline = Pipeline::wrap($handler, [$accessLog, $authorization]);
$server = new Server($config, $pipeline);

Install ext-zlib and use new Thesis\Http\Server\Gzip() to negotiate gzip on a handler. It streams the compressed body and forwards trailers. Compression weakens strong ETags and removes digests of the original bytes. The middleware adds Accept-Encoding to Vary on eligible responses, including when the client receives the original body.

The first middleware receives the request first and the response last. Each layer receives handle(Request $request, Context $context, callable $next). It can use $context->errorHandler->handleError(403, $request) to format an error with the server’s configured error handler. Server middleware can return a response directly or call $next(). After that call returns or throws, the middleware can call $next() again while its own handle() is running. Overlapping calls to the same $next and calls after its handle() has returned or thrown raise a LogicException.

Each call starts at the same next layer with the same request and connection context. The server streams incoming bodies and the pipeline does not buffer them for replay. Once a layer calls takeBody(), another call on the same request throws a LogicException, even if the reader consumed no bytes. A ReplayableBody lets its owner open another reader, but the request still hands off its body only once.

When a handler deserializes the body into a DTO, retry the operation that uses the DTO after deserialization. A retry runs downstream code again, so any side effects from an earlier attempt must be safe to repeat.

Connection lifetime

The server constructor takes a Config and the request handler and does no I/O. Pass an integer port to listen on 127.0.0.1. With new Config(0), the OS chooses the port. To specify the address, pass a string such as '0.0.0.0:8080' or '[::1]:8080', or pass an InetAddress. For Unix, pass an absolute socket path such as '/run/app.sock'. Use UnixEndpoint for a relative path. Both endpoint types let you set backlog, which defaults to 511. TcpEndpoint also takes reusePort and noDelay.

$server->start($group) binds the endpoint and returns once the server is ready. A bind failure throws Thesis\Net\ListenFailed from start(). With TCP port zero, $server->address gives the assigned port.

For several listeners, pass a non-empty list of endpoints in bind order. Each endpoint can override the TLS settings and connection limit from Config. Each listener counts its own connections.

$config = new Config(endpoints: [
    new TcpEndpoint(new InetAddress('0.0.0.0', 8080)),
    new TcpEndpoint(new InetAddress('0.0.0.0', 8443), tls: $tls, maxConnections: 256),
]);

The server binds every endpoint before accepting requests. If a bind fails, it releases all sockets opened by that start. Read the bound addresses from $server->addresses in configuration order. $server->address gives the first listener's address. Each listener emits its own lifecycle events. Stopping the server closes all listeners before waiting for active exchanges under one shutdown deadline.

Call $server->stop() outside request handlers to stop accepting clients and wait for shutdown. The server closes idle sockets and lets active handlers and response writers finish until the shutdown deadline. Cancelling the serving scope also stops the server. The example uses ext-pcntl and handles SIGINT and SIGTERM by closing the listener.

If the handler throws before the final response starts, the client receives a 500. Once a final response has started, a failure closes the connection. Each connection runs independently of the others.

The event loop watches each connection for peer shutdown. After the request body is complete, EOF or a transport read failure cancels the connection task. This interrupts cancellable waits such as delay(). A client that shuts down its write side can therefore lose its response. If bytes of a pipelined request arrive, the server saves them for the next exchange and stops watching for the rest of this one.

When the handler leaves the request body unread, the server finishes writing its response and closes the connection. An echo or another streaming response may still read the request body after the handler returns. A fixed-length request is complete when its final payload byte is read. A chunked request is complete when the decoder has consumed the terminating chunk and all its trailers.

Server events

The server uses an empty dispatcher by default. Pass a Thesis\Dispatcher as the named dispatcher argument to observe events. Subscribe by the event class in Thesis\Http\Server\Event. Listeners run synchronously in the emitting task. Handlers and middleware can publish their own events to the same dispatcher with $context->dispatcher->dispatch($event).

Event When the server dispatches it
ServerStarted The listener is ready, with its bound address and whether TLS is enabled.
ServerStopping The listener has closed and graceful shutdown starts, with the number of open connections and the shutdown timeout.
ServerStopped The serving group and its connection tasks have finished. Includes the number of open connections forced closed at the shutdown deadline.
ConnectionAccepted, ConnectionClosed A connection task starts or releases its socket. Both carry the local and remote addresses.
RequestHeadRejected The parser rejected the head, before the server attempts the error response. Carries the status and parser diagnostic.
RequestStarted The server accepted a parsed request head. Carries the request, including when the server will reject its size or expectation.
RouteMatched The router is about to invoke a matched handler. Carries the request and the match, including the selected route method.
RequestEnded Processing of a parsed request ended, including cancellation and failed writes. Carries the intended final status if available, whether the whole response was written, and elapsed time since the parsed head.
TlsHandshakeFailed, ConnectionHandlingFailed An exception escaped TLS negotiation or HTTP processing. A listener can accept both with the union type TlsHandshakeFailed|ConnectionHandlingFailed. Each carries the original exception and the connection addresses.

A malformed request head never starts an exchange. A handler exception followed by a successful 500 write produces both a finished request and a server error. A handler that returns a 500 produces only the normal request events. The server dispatches RequestEnded directly when processing leaves the exchange, including on cancellation. The three request events expose the request as $event->request. Use its object identity to correlate events, including concurrent requests to the same URI. The handler receives this same object. Calling takeBody() in a listener claims the body for that listener. For an early 413 or 417 the server exposes the parsed headers and an empty body.

Server logging

Pass a PSR-3 logger to ServerLogger. It logs startup and shutdown at info, HTTP failures at error, and TLS failures and rejected request heads at debug. The TCP startup message includes a URL with the bound port. Wildcard listeners use a loopback URL and keep the bound address in the log context. Enable the optional access log to record each finished request at info, including its method, path, status, write outcome and duration in milliseconds. The path excludes the query string.

use Thesis\Dispatcher;
use Thesis\Http\Server;
use Thesis\Http\Server\ServerLogger;

$server = new Server($config, $handler, dispatcher: new Dispatcher([new ServerLogger($logger, accessLog: true)]));

Limits

Pass limits and timeouts as named arguments of Config, for example new Config($endpoint, maxConnections: 256). Sizes count bytes. Durations use Time\Duration, for example Thesis\Time\sec(5).

Option Default Applies to
maxConnections 1024 Accepted connections, including idle ones
maxRequestsPerConnection null (unlimited) Set a positive integer to limit requests per connection
maxHeadBytes 64 KiB The request line and fields, including the terminating empty line
maxBodyBytes 16 MiB Payload after decoding HTTP/1 framing
headTimeout 10 s Receipt of the complete head
idleTimeout 30 s Waiting for the next request on a persistent connection
bodyIdleTimeout 30 s A transport read while receiving the request body
writeTimeout 30 s A transport write
tlsHandshakeTimeout 10 s Negotiation when a TLS configuration is supplied
shutdownTimeout 5 s Finishing active exchanges after shutdown starts

TLS and request expectations

Pass a Thesis\Net\ServerTls configuration through the tls argument of Config to enable HTTPS. The TLS handshake runs in the task for the accepted socket. The handler can inspect the negotiated details through $context->tls. Use http/1.1 when configuring ALPN for this server.

For HTTP/1.1 uploads with Expect: 100-continue, a handler can reject a request from its headers or read its body. A body read sends the interim response if the client is waiting. A successful streaming response can also consume the request body later. The server sends Continue before that response starts. A known length above the configured limit gets 413 before the server accepts the upload. An unsupported expectation gets 417.

The server implements HTTP message exchanges. Protocol switching, CONNECT tunnels and HTTP/2 are outside this proof of concept.

HTTP/1 parsing

The client derives Host from the URI. Both client and server choose the framing from the body and trailers. Eligible HEAD and 304 responses preserve an explicit Content-Length as representation metadata. The server sends only the headers for HEAD and closes the response body without reading it. An ordinary GET handler can return its usual body for HEAD, including a stream.

The server rejects malformed request heads and closes the connection. Examples include:

  • a line that ends with a bare \n or contains a bare \r, a folded line, a space before the colon of a field;
  • a name that is not a token, a control character in a value;
  • Content-Length together with Transfer-Encoding; a Content-Length that is repeated, is a list (5, 5), has a sign or an embedded space, or has more than 18 digits;
  • a transfer coding other than exactly chunked (gzip, chunked is rejected too), and any transfer coding in HTTP/1.0;
  • an HTTP/1.1 request without Host or with two, a Host that is not a host with an optional port;
  • a target that is none of these: an RFC 3986 path, an http or https URI, * for OPTIONS, a host and a port for CONNECT; a target with a fragment or user info;
  • more than 100 fields.

For a request-target starting with a slash, the parser percent-encodes [ ] \ ^ `` `` { | } in the path or query. Browsers send these bytes unescaped (?filter[name]=x`), and an RFC 3986 URI cannot hold them.

The fields that belong to the connection, and the fields that Connection names, are removed from the headers: they are meant for this hop only, and a proxy must not forward them.

Releases

Packages

Contributors

Languages