# Requests

> A handler receives each *Request.

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

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 `RequestPart` s.

```go
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

#### `AddressFamily`

AddressFamily is the family of a peer's socket address.

[server.go:499 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L499)

```go
type AddressFamily uint8
```

#### Values

| `AddressUnknown` | | AddressUnknown means no address was read. |
| - | - | - |
| `AddressIPv4` | | AddressIPv4 is an IPv4 peer. |
| `AddressIPv6` | | AddressIPv6 is an IPv6 peer. |
| `AddressUnix` | | AddressUnix is a local socket peer. |

#### `HTTPStatus`

HTTPStatus is an HTTP status code, named or not.

[server.go:517 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L517)

```go
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` | | |

#### `Peer`

Peer 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L482)

```go
type Peer struct {
    NetworkInterfaceIndex uint
    StaticKey             NoiseKey
    Address               PeerAddress
}
```

#### `PeerAddress`

PeerAddress 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L490)

```go
type PeerAddress struct {
    Bytes  [16]byte
    Scope  uint32
    Port   uint16
    Family AddressFamily
    // contains filtered or unexported fields
}
```

#### `PercentMode`

PercentMode says whether a '+' decodes as itself, in a path, or as a space, in a query.

[server.go:464 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L464)

```go
type PercentMode int32
```

#### Values

| `PercentPath` | | PercentPath decodes a path, where '+' stays itself. |
| - | - | - |
| `PercentQuery` | | PercentQuery decodes a query value, where '+' is a space. |

#### `RequestPart`

RequestPart is one part of a multipart/form-data body, viewing the received bytes.

[server.go:514 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L514)

```go
type RequestPart struct {
    Name        []byte
    ContentType []byte
    Data        []byte
}
```

#### Struct `BodyChunk`

BodyChunk is the body bytes a pull answered, valid until the next pull.1

[server.go:838 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L838)

```go
type BodyChunk struct {
    // contains filtered or unexported fields
}
```

##### `Bytes`

Bytes are the pulled bytes, empty once the body ended.

[server.go:843 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L843)

```go
func (chunk BodyChunk) Bytes() []byte
```

#### Struct `Deferred`

Deferred 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L273)

```go
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.

##### `Close`

Close blocks until the call is final, releases its pins, and reports the call's failure.

[types.go:310 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L310)

```go
func (deferred *Deferred[Result]) Close() error
```

It is idempotent and safe after Wait.

##### `Status`

Status reports StatusDeferred until the call is final, then its final status, without blocking.

[types.go:299 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L299)

```go
func (deferred *Deferred[Result]) Status() Status
```

##### `Wait`

Wait blocks until the call is final, releases its pins, then hands back its result, the same every time it is asked.

[types.go:303 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L303)

```go
func (deferred *Deferred[Result]) Wait() (Result, error)
```

#### Struct `DetachedRequest`

DetachedRequest 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L721)

```go
type DetachedRequest struct {
    Request
}
```

Close answers 500 for one never replied to.

##### `BodyChunk`

BodyChunk 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L848)

```go
func (detached *DetachedRequest) BodyChunk() (*Deferred[BodyChunk], error)
```

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

##### `Close`

Close answers 500 if the request was never replied to.

[server.go:726 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L726)

```go
func (detached *DetachedRequest) Close() error
```

It is idempotent.

##### `ReplyParts`

ReplyParts answers with status, header lines and parts concatenated into the body, its length measured from the files, and consumes the request.

[server.go:805 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L805)

```go
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.

##### `ReplyStream`

ReplyStream 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L821)

```go
func (detached *DetachedRequest) ReplyStream(
    status HTTPStatus,
    headers []string,
) (*ReplyStream, error)
```

##### `*Body`

× 2 Body 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L558)

Inherited from `Request`

```go
func (request *DetachedRequest) Body() ([]byte, error)
```

##### `*Detach`

× 2 Detach 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L712)

Inherited from `Request`

```go
func (request *DetachedRequest) Detach() *DetachedRequest
```

##### `*Fields`

× 2 Fields 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L609)

Inherited from `Request`

```go
func (request *DetachedRequest) Fields() iter.Seq2[[]byte, []byte]
```

##### `*Header`

× 2 Header is the value of header name, matched case-insensitively, failing with StatusNotFound without one.

[server.go:596 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L596)

Inherited from `Request`

```go
func (request *DetachedRequest) Header(
    name string,
) ([]byte, error)
```

##### `*Part`

× 2 Part is part index of a multipart/form-data body, its payload undecoded.

[server.go:665 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L665)

Inherited from `Request`

```go
func (request *DetachedRequest) Part(
    index uint,
) (RequestPart, error)
```

##### `Parts*PartsCount`

× 2 PartsCount is how many parts a multipart/form-data body has, zero for any other body.

[server.go:660 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L660)

Inherited from `Request`

```go
func (request *DetachedRequest) PartsPartsCount() uint
```

##### `*Path`

× 2 Path is the path as sent, still percent-encoded, without the query.

[server.go:535 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L535)

Inherited from `Request`

```go
func (request *DetachedRequest) Path() ([]byte, error)
```

##### `Path*PathParameter`

× 2 PathParameter is the value the route's template captured under name, case-sensitive, failing with StatusNotFound without one.

[server.go:570 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L570)

Inherited from `Request`

```go
func (request *DetachedRequest) PathPathParameter(
    name string,
) ([]byte, error)
```

##### `Path*PathSegment`

× 2 PathSegment is path component index, counting from zero, failing with StatusNotFound past the last one.

[server.go:648 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L648)

Inherited from `Request`

```go
func (request *DetachedRequest) PathPathSegment(
    index uint,
) ([]byte, error)
```

##### `PathSegments*PathSegmentsCount`

× 2 PathSegmentsCount is how many path components the request has, as sent.

[server.go:642 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L642)

Inherited from `Request`

```go
func (request *DetachedRequest) PathSegmentsPathSegmentsCount() uint
```

##### `*Peer`

× 2 Peer is the interface the request arrived on, the client's key and its address, readable after its connection closed.

[server.go:629 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L629)

Inherited from `Request`

```go
func (request *DetachedRequest) Peer() (Peer, error)
```

##### `*Query`

× 2 Query is the value of query parameter name, case-sensitive and still percent-encoded, failing with StatusNotFound without one.

[server.go:583 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L583)

Inherited from `Request`

```go
func (request *DetachedRequest) Query(name string) ([]byte, error)
```

##### `Query*QueryString`

× 2 QueryString is the query after the first '?', still percent-encoded, or empty without one.

[server.go:546 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L546)

Inherited from `Request`

```go
func (request *DetachedRequest) QueryQueryString() ([]byte, error)
```

##### `*Reply`

× 2 Reply 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L684)

Inherited from `Request`

```go
func (request *DetachedRequest) Reply(
    status HTTPStatus,
    headers []string,
    body []byte,
) error
```

##### `Reply*ReplyError`

× 2 ReplyError answers with an error status, 400 or above, and a plain-text message, and consumes the request.

[server.go:699 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L699)

Inherited from `Request`

```go
func (request *DetachedRequest) ReplyReplyError(
    status HTTPStatus,
    message string,
) error
```

##### `*Verb`

× 2 Verb is the HTTP method, which tells apart the requests of a VerbAny route.

[server.go:530 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L530)

Inherited from `Request`

```go
func (request *DetachedRequest) Verb() Verb
```

#### Struct `ReplyPart`

ReplyPart 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 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L733)

```go
type ReplyPart struct {
    // contains filtered or unexported fields
}
```

##### `BytesPart`

BytesPart is bytes in memory, copied before the reply returns.

[server.go:744 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L744)

```go
func BytesPart(bytes []byte) ReplyPart
```

##### `FilePart`

FilePart is a range of a regular file the event loop reads unbuffered after the call returns.

[server.go:757 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L757)

```go
func FilePart(file FileRange) ReplyPart
```

##### `PathPart`

PathPart is a range of a file the event loop opens beneath a reply directory and closes once sent.

[server.go:772 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L772)

```go
func PathPart(path PathRange) ReplyPart
```

#### Struct `Request`

Request is one received request, answered at most once.

[server.go:475 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L475)

```go
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

#### `DecodePercent`

DecodePercent decodes the percent escapes of a path or a query value, which requests hold still encoded, into a new slice.

[ucall.go:476 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/ucall.go#L476)

```go
func DecodePercent(
    encoded []byte,
    mode PercentMode,
) ([]byte, error)
```
