Go · Requests

Requests

import "github.com/unum-cloud/ucall" 1.0.0-rc.1 · b7577426

Ask your coding agent about this page, or add the docs server to it

curl -s 'https://www.unum.cloud/docs/ucall/go/requests.md' | claude -p "How would this fit my code?"

A handler receives each *Request. Its reads view the received bytes until the reply: Verb, Path, QueryString, PathParameter, Query, Header and Body, with Peer naming the interface it arrived on, the client’s authenticated Noise key and its PeerAddress. Every read that can fail answers its value beside an error, so a missing header or parameter reports StatusNotFound and a body read on a streamed route StatusInvalidArgument. The path and query values stay percent-encoded as sent, which ucall.DecodePercent decodes, header names match case-insensitively, and the body arrives whole, decoded from chunked framing if it was sent that way. Fields yields every header field in arrival order as a name and a value, names lowercased and values trimmed, as a proxy forwards a head. PathSegmentsCount and PathSegment read the path component by component, and PartsCount and Part read a multipart/form-data body as RequestParts.

err = server.Post("/orders/{order}", func(request *ucall.Request) {
	token, err := request.Header("authorization")
	if err != nil {
		_ = request.ReplyError(ucall.HTTPStatusUnauthorized, "sign in first")
		return
	}
	order, _ := request.PathParameter("order")
	receipt := append(append(append([]byte{}, order...), " by "...), token...)
	headers := []string{"content-type: text/plain", "cache-control: no-store"}
	_ = request.Reply(ucall.HTTPStatusCreated, headers, receipt)
})

Reply and ReplyError take the request, so a request is answered at most once, and Content-Length, Date and Server are generated. A reply copies what it sends before it returns, so a body may view the request’s bytes. A handler that neither replies nor detaches its request answers 500 once it returns, and a handler that panics crashes the process, as a panic cannot unwind through the library. The library clears the request’s handle once a reply took it, a closed connection included, which reports StatusConnectionClosed; a reply it refused keeps the handle, and the handler’s return then answers 500.

API

Types

AddressFamilyAddressFamily is the family of a peer's socket address.
server.go:499 ↗
type AddressFamily uint8

Values

AddressUnknownAddressUnknown means no address was read.
AddressIPv4AddressIPv4 is an IPv4 peer.
AddressIPv6AddressIPv6 is an IPv6 peer.
AddressUnixAddressUnix is a local socket peer.
HTTPStatusHTTPStatus is an HTTP status code, named or not.
server.go:517 ↗
type HTTPStatus uint32

Values

HTTPStatusOK
HTTPStatusCreated
HTTPStatusNoContent
HTTPStatusPartialContent
HTTPStatusMovedPermanently
HTTPStatusFound
HTTPStatusNotModified
HTTPStatusBadRequest
HTTPStatusUnauthorized
HTTPStatusForbidden
HTTPStatusNotFound
HTTPStatusMethodNotAllowed
HTTPStatusTimeout
HTTPStatusConflict
HTTPStatusPreconditionFailed
HTTPStatusPayloadTooLarge
HTTPStatusRangeNotSatisfiable
HTTPStatusTooManyRequests
HTTPStatusInternalError
HTTPStatusNotImplemented
HTTPStatusBadGateway
HTTPStatusServiceUnavailable
HTTPStatusGatewayTimeout
HTTPStatusVersionNotSupported
PeerPeer is who sent a request: the interface it arrived on, the client's authenticated static key, zeroed in plaintext, and its socket address.
server.go:482 ↗
type Peer struct {
    NetworkInterfaceIndex uint
    StaticKey             NoiseKey
    Address               PeerAddress
}
PeerAddressPeerAddress is a socket address: IPv4 in the first 4 bytes, IPv6 in all 16, both in network order, with the port and the IPv6 scope; a local socket carries only its family.
server.go:490 ↗
type PeerAddress struct {
    Bytes  [16]byte
    Scope  uint32
    Port   uint16
    Family AddressFamily
    // contains filtered or unexported fields
}
PercentModePercentMode says whether a '+' decodes as itself, in a path, or as a space, in a query.
server.go:464 ↗
type PercentMode int32

Values

PercentPathPercentPath decodes a path, where '+' stays itself.
PercentQueryPercentQuery decodes a query value, where '+' is a space.
RequestPartRequestPart is one part of a multipart/form-data body, viewing the received bytes.
server.go:514 ↗
type RequestPart struct {
    Name        []byte
    ContentType []byte
    Data        []byte
}
StructBodyChunkBodyChunk is the body bytes a pull answered, valid until the next pull.1
server.go:838 ↗
type BodyChunk struct {
    // contains filtered or unexported fields
}
BytesBytes are the pulled bytes, empty once the body ended.
server.go:843 ↗
func (chunk BodyChunk) Bytes() []byte
StructDeferredDeferred is a submitted call, which holds its outcome and inputs until it is final, owned by the one goroutine that polls or waits on it.3
types.go:273 ↗
type Deferred[Result any] struct {
    // contains filtered or unexported fields
}

Status polls without blocking, Wait blocks until the call is final and hands back its result, and Close waits the same way and drops it. A Deferred dropped without Wait or Close is released by the collector once the call is final, never blocking on it: until then every later collection checks it again.

CloseClose blocks until the call is final, releases its pins, and reports the call's failure.
types.go:310 ↗
func (deferred *Deferred[Result]) Close() error

It is idempotent and safe after Wait.

StatusStatus reports StatusDeferred until the call is final, then its final status, without blocking.
types.go:299 ↗
func (deferred *Deferred[Result]) Status() Status
WaitWait blocks until the call is final, releases its pins, then hands back its result, the same every time it is asked.
types.go:303 ↗
func (deferred *Deferred[Result]) Wait() (Result, error)
StructDetachedRequestDetachedRequest is a request taken off its polling goroutine, and the only owner of the verbs that may finish later: ReplyParts, ReplyStream and BodyChunk.20
server.go:721 ↗
type DetachedRequest struct {
    Request
}

Close answers 500 for one never replied to.

BodyChunkBodyChunk pulls the body bytes decoded since the last pull, final once they arrive and empty once the body ended; on a buffered route the first pull is the whole body.
server.go:848 ↗
func (detached *DetachedRequest) BodyChunk() (*Deferred[BodyChunk], error)

A pull on the polling goroutine finding nothing fails with StatusWouldBlock instead.

CloseClose answers 500 if the request was never replied to.
server.go:726 ↗
func (detached *DetachedRequest) Close() error

It is idempotent.

ReplyPartsReplyParts answers with status, header lines and parts concatenated into the body, its length measured from the files, and consumes the request.
server.go:805 ↗
func (detached *DetachedRequest) ReplyParts(
    status HTTPStatus,
    headers []string,
    parts []ReplyPart,
) (*Deferred[struct{}], error)

It is final at once for bytes alone, and with a file or path part stays deferred until every part is sent; a part failing before the head left replaces the reply with 404, 416 or 500, and the Deferred reports the cause.

ReplyStreamReplyStream sends the status line and header lines and opens a body appended part by part, which is chunked unless a Content-Length line declares its length.
server.go:821 ↗
func (detached *DetachedRequest) ReplyStream(
    status HTTPStatus,
    headers []string,
) (*ReplyStream, error)
*Body× 2Body is the body, decoded from chunked framing if it arrived that way; a streamed route refuses it, as DetachedRequest.BodyChunk pulls its body.
server.go:558 ↗

Inherited from Request

func (request *DetachedRequest) Body() ([]byte, error)
*Detach× 2Detach hands the request to a goroutine that may wait, where it gains the replies that may finish later; the polling goroutine itself must never wait on them.
server.go:712 ↗

Inherited from Request

func (request *DetachedRequest) Detach() *DetachedRequest
*Fields× 2Fields yields every header field line in arrival order, repeated names apart, each name lowercased as the parser keeps it and its value trimmed.
server.go:609 ↗

Inherited from Request

func (request *DetachedRequest) Fields() iter.Seq2[[]byte, []byte]
*Part× 2Part is part index of a multipart/form-data body, its payload undecoded.
server.go:665 ↗

Inherited from Request

func (request *DetachedRequest) Part(
    index uint,
) (RequestPart, error)
Parts*PartsCount× 2PartsCount is how many parts a multipart/form-data body has, zero for any other body.
server.go:660 ↗

Inherited from Request

func (request *DetachedRequest) PartsPartsCount() uint
*Path× 2Path is the path as sent, still percent-encoded, without the query.
server.go:535 ↗

Inherited from Request

func (request *DetachedRequest) Path() ([]byte, error)
Path*PathParameter× 2PathParameter is the value the route's template captured under name, case-sensitive, failing with StatusNotFound without one.
server.go:570 ↗

Inherited from Request

func (request *DetachedRequest) PathPathParameter(
    name string,
) ([]byte, error)
Path*PathSegment× 2PathSegment is path component index, counting from zero, failing with StatusNotFound past the last one.
server.go:648 ↗

Inherited from Request

func (request *DetachedRequest) PathPathSegment(
    index uint,
) ([]byte, error)
PathSegments*PathSegmentsCount× 2PathSegmentsCount is how many path components the request has, as sent.
server.go:642 ↗

Inherited from Request

func (request *DetachedRequest) PathSegmentsPathSegmentsCount() uint
*Peer× 2Peer is the interface the request arrived on, the client's key and its address, readable after its connection closed.
server.go:629 ↗

Inherited from Request

func (request *DetachedRequest) Peer() (Peer, error)
*Query× 2Query is the value of query parameter name, case-sensitive and still percent-encoded, failing with StatusNotFound without one.
server.go:583 ↗

Inherited from Request

func (request *DetachedRequest) Query(name string) ([]byte, error)
Query*QueryString× 2QueryString is the query after the first '?', still percent-encoded, or empty without one.
server.go:546 ↗

Inherited from Request

func (request *DetachedRequest) QueryQueryString() ([]byte, error)
*Reply× 2Reply answers with status, full header lines like "content-type: text/plain" and body, and consumes the request; the length, date and server lines are generated.
server.go:684 ↗

Inherited from Request

func (request *DetachedRequest) Reply(
    status HTTPStatus,
    headers []string,
    body []byte,
) error
Reply*ReplyError× 2ReplyError answers with an error status, 400 or above, and a plain-text message, and consumes the request.
server.go:699 ↗

Inherited from Request

func (request *DetachedRequest) ReplyReplyError(
    status HTTPStatus,
    message string,
) error
*Verb× 2Verb is the HTTP method, which tells apart the requests of a VerbAny route.
server.go:530 ↗

Inherited from Request

func (request *DetachedRequest) Verb() Verb
StructReplyPartReplyPart is one part of a reply body: bytes in memory, a range of the caller's unbuffered descriptor, or a range of a file beneath one of the interface's reply directories.3
server.go:733 ↗
type ReplyPart struct {
    // contains filtered or unexported fields
}
BytesPartBytesPart is bytes in memory, copied before the reply returns.
server.go:744 ↗
func BytesPart(bytes []byte) ReplyPart
FilePartFilePart is a range of a regular file the event loop reads unbuffered after the call returns.
server.go:757 ↗
func FilePart(file FileRange) ReplyPart
PathPartPathPart is a range of a file the event loop opens beneath a reply directory and closes once sent.
server.go:772 ↗
func PathPart(path PathRange) ReplyPart
StructRequestRequest is one received request, answered at most once.
server.go:475 ↗
type Request struct {
    // contains filtered or unexported fields
}

Its reads view the received bytes until the reply, which consumes it; a handler that neither replies nor detaches it answers 500.

Functions

DecodePercentDecodePercent decodes the percent escapes of a path or a query value, which requests hold still encoded, into a new slice.
ucall.go:476 ↗
func DecodePercent(
    encoded []byte,
    mode PercentMode,
) ([]byte, error)