HTTP Server and Client
Spice ships a blocking HTTP/1.1 server and client in std/net/http-server and std/net/http-client, built directly
on top of the plain TCP sockets in std/net/socket. Both understand request/response framing via Content-Length
and chunked transfer encoding, so you get a working HTTP stack without pulling in any third-party dependency.
This tutorial builds a small server with a few routes, and a client that talks to it, as two separate programs - which is how you would run them in practice.
TLS
HttpClient and HttpServer both speak TLS via std/net/tls, built on the OpenSSL bindings in
std/bindings/openssl - see TLS / HTTPS below. This adds a build-time dependency on OpenSSL
(libssl-dev on Debian/Ubuntu).
A minimal server¶
Every server is built around the HttpServer struct. Construct it with a port, register routes on it, then start
it and let it run:
serve registers a GET route that always answers with the same, fixed piece of content - handy for static pages.
start binds the port, and run then serves connections one at a time, forever, until something calls stop or a
connection can no longer be accepted. Run it with:
The process keeps running in the foreground; leave it there and press ++ctrl+c++ once you are done with the tutorial.
A minimal client¶
HttpClient is the counterpart on the other side. Every call opens its own connection, sends one request, and
closes the connection again once the response has arrived:
With the server from the previous section still running, open a second terminal and run the client:
Adding routes¶
Besides serve, HttpServer has one method per HTTP method - get, post, put, patch and delete - that
takes a path and a handler lambda of type p(const HttpRequest&, HttpResponse&). The handler fills in the response
that is passed to it:
getQueryParam reads and percent-decodes a value straight out of the query string, so a request to
/greet?name=Spice answers with Hello, Spice!, while a plain /greet falls back to Hello, stranger!.
Routing is exact-match
A route only answers the exact path it was registered for - /a and /a/ are different routes, path
parameters such as /users/{id} are not supported, and the query string never takes part in the match. Read
dynamic parts of the path yourself out of request.getPath(), and query parameters via getQueryParam.
A path that exists for another method answers 405 Method Not Allowed automatically, and a HEAD request is
answered from the matching GET route with the body dropped - you don't need to register those cases yourself.
Request and response bodies¶
A handler reads the request body straight off the request.body field, and hands a response body to
response.setBody together with its media type. setJsonBody and setHtmlBody are shorthands for the two most
common cases:
| Spice | |
|---|---|
std/net/http defines constants for the common status codes (STATUS_OK, STATUS_CREATED, STATUS_NOT_FOUND,
STATUS_INTERNAL_SERVER_ERROR, ...) and media types (CONTENT_TYPE_TEXT, CONTENT_TYPE_HTML, CONTENT_TYPE_JSON,
...), so you rarely have to spell out a raw number or MIME string yourself.
Handling unmatched requests¶
Without any configuration, a request that matches no route gets a plain 404. Register a custom handler with
setNotFoundHandler to answer it differently:
| Spice | |
|---|---|
The status code is already set to 404 by the time your handler runs - you only need to fill in the body.
Sending more than GET¶
HttpClient mirrors the server's set of methods - get, head, post, put, patch and delete - plus a
request method that takes an arbitrary HttpMethod for anything that does not fit the named ones. post, put
and patch take a body and a content type, just like setBody does on the server side:
A handful of public fields on HttpClient let you adjust its behavior:
| Spice | |
|---|---|
defaultHeaders fields are only added to a request if it does not already carry a field with that name, so a
one-off request can always override them.
Header fields and message framing¶
Header fields often carry untrusted input, e.g. a redirect target taken from a query parameter. When a request or a response is written to the wire, such input cannot break the message apart:
- CR, LF and NUL in field values, in the reason phrase and in the HTTP version are replaced with spaces, so a value can never end its line early and inject further header fields or a whole message.
- A field, whose name is not a valid token (RFC 9110, section 5.6.2), is left out.
- Spaces and control characters in the request target are percent-encoded.
On the receiving side, a message, whose Content-Length fields are malformed or announce different lengths, is rejected,
since it is ambiguous where its body ends - which is how request smuggling works. receiveRequest and receiveResponse
return an error then, and HttpServer answers such a request with 400 Bad Request. Announcing the same length more
than once, e.g. as Content-Length: 5, 5, is fine.
TLS / HTTPS¶
HttpClient.get (and the other request methods) transparently use TLS whenever the URL starts with https:// - no
extra code needed on the client side beyond the URL itself:
| Spice | |
|---|---|
By default, the server's certificate is verified against the operating system's trust store, and its host name is
checked against the URL. On Windows, that is the certificate store of Windows: the certificates it trusts for server
authentication. The SSL_CERT_FILE and SSL_CERT_DIR environment variables replace the trust store of the operating
system with the given PEM file or directory. Point verification at a specific CA bundle instead - for example to talk to a server with
a self-signed certificate - with trustedCaFile:
| Spice | |
|---|---|
There is no way to switch verification off: a client that does not verify the server it talks to gets no real
confidentiality guarantee, so std/net/tls does not offer that option.
To serve https instead of plain http, call useTls with a certificate and private key (PEM files) before start:
| Spice | |
|---|---|
Everything else - routes, handlers, start/run/stop - stays the same; only the listening socket's connections
are now TLS-handshaked before their request is read.
Host name resolution¶
The client accepts host names, IPv4 addresses and IPv6 addresses, the latter in brackets like in any URL
(http://[::1]:8080/). openClientSocket in std/net/socket resolves host names with the resolver of std/net/dns,
which is written in Spice: it looks the name up in the hosts file and asks the name servers for its IPv4 (A) and IPv6
(AAAA) addresses, over UDP with a fallback to TCP for large answers. Addresses from the hosts file win over the ones
from DNS, and the names of the search list are asked for in their order. For each name, the IPv4 addresses are tried
first, one after the other; the IPv6 addresses are only looked up, if none of them accepts the connection. The first
name, that has any address, is the last one to be tried.
Host names have to be fully spelled out: shorthand forms of IPv4 addresses, that the C library accepts, like 127.1
or 0x7f000001, are rejected as malformed host names, also on Windows.
On Linux and macOS, the resolver reads /etc/hosts and the name servers from /etc/resolv.conf. Windows has no
resolv.conf, so there the name servers and DNS suffixes of the network adapters, that are up, take its place, and the
hosts file is read from %SystemRoot%\System32\drivers\etc\hosts.
The resolver does not go through the name resolution of the C library or the operating system. On Linux, this keeps
statically linked programs working on systems with an older glibc than the one they were linked against. On the other
hand, name sources other than the hosts file and DNS, like mDNS for .local names, are not available, and resolution
policies of the operating system are not applied: on macOS, name servers that only apply to certain domains (e.g. the
ones of a VPN, see scutil --dns) are not consulted, and on Windows, the Name Resolution Policy Table and DNS over HTTPS
are not taken into account.
You can also use the resolver directly, e.g. to look up the addresses of a host without connecting to it:
To connect with a resolver of your own, e.g. one with a fixed set of name servers, pass it to openClientSocket.
Replace 192.0.2.53, an address reserved for documentation, with the address of your name server:
| Spice | |
|---|---|
Putting it all together¶
server.spice:
client.spice:
Run the server in one terminal and the client in another:
| Bash | |
|---|---|
Skipping error handling in a demo
The full example above calls unwrap() straight away for brevity. unwrap() aborts the program if the
Result holds an error, so in real code check isErr() first, the way the earlier sections do.