website/docs/primitives.md

2.6 KiB

Handy-Http Primitives

DDoc Reference

The Primitives library provides the foundational set of types and interfaces for Handy-Http. Most notably, the Primitives component defines the ServerHttpRequest and ServerHttpResponse structs, and the HttpRequestHandler interface. Together, these symbols form the basis for a common HTTP layer, loosely inspired by Java's Servlet specification. All other Handy-Http components build on top of Primitives' types to implement request handling, response writing, filtering, and all manner of other conveniences you'd expect in a web framework.

!!! info "Streams" Handy-Http makes extensive use of the streams library for low-level byte input and output operations. This library was also written by Andrew specifically for Handy-Http, and it'll be familiar to programmers coming from Java or other languages that have a stream concept.

In general, we *read* HTTP requests from an input stream, and *write* responses to an output stream. To allow for flexibility, the Primitives component only refers to streams using their object-oriented interface types, i.e. `InputStream!ubyte` and `OutputStream!ubyte`.

Requests

Whenever Handy-Http receives an HTTP request from a client, it will store that request content in a ServerHttpRequest which contains the client's address, HTTP method, requested URL, headers, query parameters, and an input stream for reading the request's body content, if available.

Responses

To respond to a client's HTTP request, you'll use a ServerHttpResponse, which allows you to provide a status and headers. Response body content is written to the response's output stream.

Request Handlers

We combine the request and response types into one functional interface, HttpRequestHandler, which is defined as:

interface HttpRequestHandler {
    void handle(ref ServerHttpRequest request, ref ServerHttpResponse response);
}

The job of a request handler is to read in an HTTP request, do some logic, and write to the given response. With the use of streams for I/O abstraction, request handlers are the basis for all of Handy-Http, and to achieve more complex behavior, one can simply extend or wrap another request handler.