HTTP::Core — API

HTTP::Core — API reference

Everything here is verified against the tree at 0.1.x on Rakudo 2026.09 (MoarVM). Anything not listed is private: methods whose names start with ! are implementation detail and may change without notice.

Two conventions run through the whole library:

  • Offsets are bytes. .consumed, .body-offset, .name-len and friends count bytes, never grapheme clusters. Searching a wire image for a terminator must be done on a Buf, not on a decoded Str (see README → Byte offsets, not graphemes).

  • Headers are ordered pairs. header-pairs returns the wire verbatim, in order, duplicates preserved. header('X') returns the first value; header-values('X') returns all of them.

1. Facade — use HTTP::Core

The short surface. Everything here is exported.

RoutineReturnsPurpose
core-version()StrVersion string reported by the C kernel itself
library-path()StrAbsolute path of the shared library the binding resolved
assert-abi()BoolCompares kernel ABI against this build; dies on mismatch
parse-request(Blob $raw)HTTP::Core::RequestParse one request head; throws X::Incomplete / X::ParseError
`encode-request(args)`BufBuild a request from method / target / headers / body
parse-response(Blob $raw, :$head)HTTP::Core::ResponseParse a response; :head for HEAD replies
decode-response(Blob $raw, :$head)HTTP::Core::ResponseAlias of parse-response
response-extent(Response $r)IntBytes this response occupies on the wire, or -1 if the head does not say
new-client(*%opt)HTTP::Core::ClientConvenience constructor

free-port() lives in HTTP::Core::Server (it binds port 0, reads the assigned port, closes) and is exported from there.

2. HTTP::Core::Request

A value object over your buffer: no bytes are copied out until you ask for a string.

MethodReturnsNotes
methodStrRequest method, uppercased by the caller or as sent
targetStrRequest target exactly as sent (/a?b=1)
pathStrAlias of target
path-onlyStrTarget minus the query string
query-stringStrEverything after ?, empty when absent
http-versionStr1.0 or 1.1
header-countIntNumber of header fields
header-name(Int $i) / header-value(Int $i)StrIndexed access, wire order
header(Str $name)StrFirst value, case-insensitive name match
header-pairsListOrdered Pairs, duplicates preserved
consumed / body-offsetIntHead length in bytes; the body starts here
bodyBufBytes after the head, as far as the buffer goes
content-lengthIntParsed Content-Length, or a sentinel when absent
keep-aliveBoolWhether HTTP/1.x allows reuse for this request
is-completeBoolHead present and full body present
encode(:$close)BufRe-emit the request bytes; :close appends Connection: close
encode-reference(:$close)BufSlow, obvious reimplementation used as a test oracle

encode does not rebuild the head from strings: the parser left a table of (offset, length) pairs over your buffer and the kernel copies each field out of it, so a parse → encode round trip is one memcpy per field.

3. HTTP::Core::Response

Constructing

FormProduces
Response.new(:$body, :%headers, :$status)Anything; headers is a hash or pair list
Response.text($s, $status = 200, *%headers)text/plain; charset=utf-8
Response.html($s, $status = 200, *%headers)text/html; charset=utf-8
Response.json($s, $status = 200, *%headers)application/json — pass a string, not a structure
Response.bytes($blob, $type, $status)Octet stream
Response.no-content($status = 204)Bodyless status
$res.with-body(...)Copy of a response with a different body

Reading

MethodReturnsNotes
statusIntStatus code
reasonStrReason phrase, derived from the code when the peer omitted it
bodyBlobBody bytes, as far as the buffer goes
body-bytesBlobSame bytes, framed view
header(Str $name)StrFirst value
header-values(Str $name)ListEvery value, in order
header-pairsListWire order, duplicates preserved
framingStrno-body | content-length | chunked | until-close
is-completeBoolEvery body byte present yet?
usableBoolWhether the connection may be reused
http-versionStr1.0 / 1.1

Serialising

MethodNotes
payload(Bool $keep-alive = True)Head + body as bytes, ready for a socket
payload-raku(...)The same, built with string operations
Response.parse($raw, :$head)Parse a received response

4. HTTP::Core::Router

MethodNotes
add($method, $pattern, &handler)$method is a verb or * for any
get / post / put / patch / delete / anyVerb shortcuts
match($method, $path)Returns the handler and captured params
allowed-methods($path)Feeds the Allow header on a 405
routesHow many routes are registered
patternsPattern list, in registration order

Patterns: literal segments, :name for one segment, * for one wildcard segment, * at the end of a pattern to capture the rest of the path (/files/* → %p<*>). Handlers are called as -> $req, %params { … } and may return a Response, a Str or a Blob.

5. HTTP::Core::Server

AttributeDefaultMeaning
host127.0.0.1Bind address
port8080Bind port; free-port() picks an unused one
routernew RouterThe route table
max-head64 KiBHead bigger than this gets 431
max-body8 MiBContent-Length bigger than this gets 413
transportTransport::TCPSwap in Transport::InMemory for tests
debugFalseLog accept/drop pairs
MethodNotes
startArms the listener and returns immediately
stopStops accepting; open connections are dropped
runningAccepting right now?
bind-errorWhy the bind failed, when it did
connectionsLive entries in the connection registry
drop-connectionsForce-close everything outstanding, returns the count
handle($req)Dispatch one request without a socket (useful in tests)
serve-transport($transport)Run the loop over an injected transport

free-port() is exported for scripts and tests.

6. HTTP::Core::Client

AttributeDefaultMeaning
timeout10Whole request, every hop; <= 0 disables
connect-timeout3TCP/TLS connect
idle-timeout15Pooled connection lifetime; keep it below the server's keep-alive
followTrueFollow redirects
insecureFalseSkip certificate verification (TLS transport only)
ca-fileunsetExtra CA bundle
debugFalseLog transport-level events
MethodReturns
get / head / post / put / patch / delete / optionsPromise of Response
request($method, $url, *%opt)Promise of Response
poolThe HTTP::Core::Pool in use
closeClose every pooled connection
closedWhether the pool is closed

Per-request options for request:

OptionTypeNotes
:headershash or pair listAdded to the generated head
:bodyBlob or StrStr is encoded UTF-8
:jsonanything JSON::Fast serialisesSets Content-Type: application/json
:timeoutRealThis request only
:max-redirectsIntThis request only
:followBoolThis request only

Failures arrive as a broken Promise carrying a HTTP::Core::X exception, so try await $client.get($url) and an X::Base check is enough to classify them.

7. HTTP::Core::Pool

MethodNotes
acquire($origin, :$timeout)Promise of a Lease
release($lease, :$force)Return or discard a lease
close / closedWhole-pool lifecycle
idle-count($origin) / active-count($origin)Live counters
waiting($origin?)Waiters queued for a lease
stats / metrics / metrics-for($origin)Snapshots for logging and benchmarks
reuse-rateFraction of requests that avoided a new connection

8. Framing, Connection, Transport

ModuleRole
HTTP::Core::FramingMessage boundaries: Buf in, Outcome out, no promises
HTTP::Core::Framing::ResponseThe same boundary rules for responses
HTTP::Core::ConnectionOne socket: buffer, parked promises, monotonic serial
HTTP::Core::TransportRole: incoming / write / close / id
HTTP::Core::Transport::TCPIO::Socket::Async implementation
HTTP::Core::Transport::TLSThe same over IO::Socket::Async::SSL
HTTP::Core::Transport::InMemoryA transport with no socket; server and client in one process

Connection.serial exists because a socket object's address is reusable: the registry is keyed on a monotonic integer, so a closed connection can never be confused with a newer one at the same address. t/17-registry-release.rakutest is the regression test.

9. Exceptions — use HTTP::Core::X

ClassRaised when
X::BaseParent of all of them; catch this to log once
X::IncompleteValid so far, feed more bytes
X::ParseErrorMalformed; answer 400
X::NetworkConnect or socket failure
X::TimeoutDeadline expired
X::ProtocolThe peer said something HTTP does not allow
X::TruncatedBody shorter than its framing promised
X::RedirectRedirect chain gave up (:max-redirects)
X::ClosedUsed a closed pool or connection
X::InvalidUrlURL did not parse

10. Environment variables

VariableUsed byEffect
HTTP_CORE_LIBHTTP::Core::NativeAbsolute path of the shared library to load, bypassing the search
CCBuild.rakumodCompiler for the kernel: zig cc, gcc, clang
DEBUGexamples/registry-watch.raku1 prints accept/drop lines with matching conn#N
PORT / DEMOexamples/hello-server.rakuBind port; seconds to serve before exiting

11. Where to look next

CommandShows
raku -Ilib examples/serve.raku --helpArgument list for the full server example
raku -Ilib examples/client.raku --helpArgument list for the client example
raku -Ilib examples/client.raku --self-testEnd-to-end smoke test, no network needed
raku -Ilib examples/registry-watch.rakuThe connection registry filling and emptying
prove -e 'raku -Ilib' t/*.rakutestThe whole suite
bench/RESULTS.md, bench/RESULTS-CRO.mdNumbers and post-mortems

HTTP::Core v0.1.0

Zero-copy HTTP/1.x request parser with a hand-written C kernel bound through NativeCall, no shim layer.

Authors

    License

    MIT

    Dependencies

    Compress::ZlibJSON::Fast

    Test Dependencies

    Provides

    • HTTP::Core
    • HTTP::Core::Bytes
    • HTTP::Core::Client
    • HTTP::Core::Client::URL
    • HTTP::Core::Codec
    • HTTP::Core::Codec::Content
    • HTTP::Core::Codec::Raku
    • HTTP::Core::Connection
    • HTTP::Core::Deadline
    • HTTP::Core::Framing
    • HTTP::Core::Framing::Response
    • HTTP::Core::Native
    • HTTP::Core::Pool
    • HTTP::Core::Request
    • HTTP::Core::Response
    • HTTP::Core::Router
    • HTTP::Core::Server
    • HTTP::Core::Transport
    • HTTP::Core::Transport::InMemory
    • HTTP::Core::Transport::TCP
    • HTTP::Core::Transport::TLS
    • HTTP::Core::X

    The Camelia image is copyright 2009 by Larry Wall. "Raku" is a trademark of the Yet Another Society. All rights reserved.

    Built with Podlite — the markup and publishing tools behind this site.