gdDocumentation0.8.0

API reference

GD.web

Entry for building websites and Web APIs, with routes, static files, gdhtml templates, sessions, CSRF, JWT, rate limiting, and input validation.

Methods

app

app() -> GDWebApp

Create a routed web application.

Parameters

No parameters.

Return value

GDWebApp

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

server

server() -> GDWebServer

Create a raw HTTP server.

Parameters

No parameters.

Return value

GDWebServer

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

text

text(body: String, status: int = 200) -> GDWebResponse

Create a plain-text HTTP response. Use it for text output that should not be interpreted as HTML.

Parameters

NameTypeDefaultDescription
bodyStringRequiredResponse text.
statusint200HTTP status code.

Return value

GDWebResponse

A GDWebResponse with a plain-text content type.

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

See also

html

html(body: String, status: int = 200) -> GDWebResponse

Create a response from HTML that has already been rendered. This helper does not parse a template or escape arbitrary text: escape untrusted values or use a template before calling it.

Parameters

NameTypeDefaultDescription
bodyStringRequiredComplete HTML response text.
statusint200HTTP status code.

Return value

GDWebResponse

A GDWebResponse with an HTML content type.

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

See also

json

json(data: Variant, status: int = 200) -> GDWebResponse, Err

Encode a value into a JSON HTTP response. This operation can fail during serialization; return its result directly from a handler to let the application error boundary handle the failure.

Parameters

NameTypeDefaultDescription
dataVariantRequiredValue to serialize as JSON.
statusint200HTTP response status, default 200.

Return value

GDWebResponse, Err

A GDWebResponse on success.

Suspends only the calling routine until the operation completes. No explicit await is needed.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

Unsupported values or invalid JSON values produce Err. Do not discard the error and use the response alone.

Examples

func hello(_req):
    return GD.web.json({"message": "Hello, world!"})

See also

bytes

bytes(body: PackedByteArray, type: String = "application/octet-stream", status: int = 200) -> GDWebResponse

Create a binary response.

Parameters

NameTypeDefaultDescription
bodyPackedByteArrayRequiredContent to write or include in the response.
typeString"application/octet-stream"Media type of the response body.
statusint200HTTP response status code.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

stream

stream(producer: Callable, length: int = -1, type: String = "application/octet-stream", status: int = 200) -> GDWebResponse

Create a lazy response from a producer writing bytes into its response Writer.

Create a lazy response producer called once with a GDWebWriter. Write PackedByteArray chunks and return void or a value and Err when finished. length=-1 selects unknown-length framing. The producer may await and should observe request-context cancellation; HEAD and bodyless statuses do not invoke it.

Parameters

NameTypeDefaultDescription
producerCallableRequiredCallable receiving the response Writer and producing body chunks.
lengthint-1Declared body length in bytes; -1 means the length is not known in advance.
typeString"application/octet-stream"Media type of the response body.
statusint200HTTP response status code.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

redirect

redirect(to: String, status: int = 302, away: bool = false) -> GDWebResponse

Create a redirect response.

Parameters

NameTypeDefaultDescription
toStringRequiredDestination selected by the operation.
statusint302HTTP response status code.
awayboolfalseWhether an external redirect destination is permitted.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

guard

guard(reply: GDWebResponse) -> GDWebResponse

Add basic security headers to a response.

Parameters

NameTypeDefaultDescription
replyGDWebResponseRequiredResponse value to extend or return.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

not_found

not_found(msg: String = "Not Found") -> GDWebResponse

Create a 404 response.

Parameters

NameTypeDefaultDescription
msgString"Not Found"Message text associated with this operation.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

add_header

add_header(reply: GDWebResponse, name: String, value: Variant) -> GDWebResponse

Append another response header with the same name.

Parameters

NameTypeDefaultDescription
replyGDWebResponseRequiredResponse value to extend or return.
nameStringRequiredHeader name or the name used to store a validated value on the request.
valueVariantRequiredValue to store, serialize, validate or pass to the operation described above.

Return value

GDWebResponse

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

view

view(path: String, data: Dictionary = {  }, status: int = 200, renderer: Callable = null) -> GDWebResponse, Err

Load an HTML template, render it with the supplied data, and create an HTTP response. Template expressions escape inserted data according to their output context.

Parameters

NameTypeDefaultDescription
pathStringRequiredTemplate file path.
dataDictionary{ }Values made available to template expressions.
statusint200HTTP status for a successful rendering.
rendererCallablenullOptional custom rendering callable; null selects the built-in renderer.

Return value

GDWebResponse, Err

A rendered GDWebResponse.

Suspends only the calling routine until the operation completes. No explicit await is needed.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

File access, template parsing and rendering errors are preserved as Err.

Examples

func page(_req):
    return GD.web.view("index.html", {"name": "world"})

See also

view_async

view_async(path: String, data: Dictionary = {  }, status: int = 200, renderer: Callable = null) -> await GDWebResponse, Err

Load an HTML template, render it with the supplied data, and create an HTTP response. Template expressions escape inserted data according to their output context.

Parameters

NameTypeDefaultDescription
pathStringRequiredTemplate file path.
dataDictionary{ }Values made available to template expressions.
statusint200HTTP status for a successful rendering.
rendererCallablenullOptional custom rendering callable; null selects the built-in renderer.

Return value

await GDWebResponse, Err

A rendered GDWebResponse.

Returns a Signal. Use await to receive the completion value shown in the signature.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

File access, template parsing and rendering errors are preserved as Err.

Examples

func page(_req):
    return GD.web.view("index.html", {"name": "world"})

See also

json_async

json_async(data: Variant, status: int = 200) -> await GDWebResponse, Err

Encode a value into a JSON HTTP response. This operation can fail during serialization; return its result directly from a handler to let the application error boundary handle the failure.

Parameters

NameTypeDefaultDescription
dataVariantRequiredValue to serialize as JSON.
statusint200HTTP response status, default 200.

Return value

await GDWebResponse, Err

A GDWebResponse on success.

Returns a Signal. Use await to receive the completion value shown in the signature.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

Unsupported values or invalid JSON values produce Err. Do not discard the error and use the response alone.

Examples

func hello(_req):
    return GD.web.json({"message": "Hello, world!"})

See also

error_status

error_status(error: Err) -> int

Return the HTTP status corresponding to an Err.

Parameters

NameTypeDefaultDescription
errorErrRequiredError value to classify when choosing an HTTP status.

Return value

int

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

jwt

jwt(key: Variant, opts: Dictionary = {  }) -> GDWebMiddleware

Create middleware that verifies bearer JWTs.

Parameters

NameTypeDefaultDescription
keyVariantRequiredSigning or verification key accepted by the configured JWT algorithm.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

An HS256 key is at least 32 bytes. The JSON and the signature are both validated. leeway is finite and 0 or more.

jwt_sign

jwt_sign(claims: Dictionary, key: Variant, opts: Dictionary = {  }) -> String, Err

Sign claims into a JWT.

Parameters

NameTypeDefaultDescription
claimsDictionaryRequiredJWT claims to sign, including any configured validity timestamps.
keyVariantRequiredSigning or verification key accepted by the configured JWT algorithm.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

String, Err

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

ttl is 0 or more.

jwt_verify

jwt_verify(token: String, key: Variant, opts: Dictionary = {  }) -> Dictionary, Err

Verify a JWT and return its claims.

Parameters

NameTypeDefaultDescription
tokenStringRequiredEncoded JWT to verify before using its claims.
keyVariantRequiredSigning or verification key accepted by the configured JWT algorithm.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary, Err

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

jwt_sign_async

jwt_sign_async(claims: Dictionary, key: Variant, opts: Dictionary = {  }) -> await String, Err

Sign claims into a JWT.

Parameters

NameTypeDefaultDescription
claimsDictionaryRequiredJWT claims to sign, including any configured validity timestamps.
keyVariantRequiredSigning or verification key accepted by the configured JWT algorithm.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

await String, Err

Returns a Signal. Use await to receive the completion value shown in the signature.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

ttl is 0 or more.

jwt_verify_async

jwt_verify_async(token: String, key: Variant, opts: Dictionary = {  }) -> await Dictionary, Err

Verify a JWT on a CPU worker.

Parameters

NameTypeDefaultDescription
tokenStringRequiredEncoded JWT to verify before using its claims.
keyVariantRequiredSigning or verification key accepted by the configured JWT algorithm.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

await Dictionary, Err

Returns a Signal. Use await to receive the completion value shown in the signature.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

csrf

csrf(opts: Dictionary = {  }) -> GDWebMiddleware

Create CSRF middleware that permits only same-origin writes.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

sessions

sessions(opts: Dictionary = {  }) -> GDWebSessionStore

Create a cookie-session store and middleware.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

GDWebSessionStore

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

total and per_user accept 1..2147483647; idle and life accept 1..9223372036 seconds. Session values are string and integer identifiers. Sessions live in the process and are not shared across --workers.

rate

rate(opts: Dictionary = {  }) -> GDWebMiddleware

Create a per-key fixed-window rate limiter.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

limit and an explicit keys accept 1..2147483647. Keys live in the process and are not shared across --workers.

text_rule

text_rule(opts: Dictionary = {  }) -> Dictionary

Create a text-length validation rule.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

int_rule

int_rule(opts: Dictionary = {  }) -> Dictionary

Create an integer-range validation rule.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

number_rule

number_rule(opts: Dictionary = {  }) -> Dictionary

Create a numeric-range validation rule.

Parameters

NameTypeDefaultDescription
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

bool_rule

bool_rule() -> Dictionary

Create a boolean validation rule.

Parameters

No parameters.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

list_rule

list_rule(item: Dictionary = {  }, opts: Dictionary = {  }) -> Dictionary

Create an array item and length validation rule.

Parameters

NameTypeDefaultDescription
itemDictionary{ }Item to inspect or the item rule applied to collection elements.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

object_rule

object_rule(fields: Dictionary, opts: Dictionary = {  }) -> Dictionary

Create an object-field validation rule.

Parameters

NameTypeDefaultDescription
fieldsDictionaryRequiredObject field names mapped to their validation rules.
optsDictionary{ }Named options for this operation. Omitted entries use their documented defaults.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

optional

optional(rule: Dictionary, fallback: Variant = null) -> Dictionary

Add a default value for missing input to a rule.

Parameters

NameTypeDefaultDescription
ruleDictionaryRequiredValidation rule describing the accepted input.
fallbackVariantnullValue returned when the requested value is unavailable or omitted.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

one_of

one_of(values: Array) -> Dictionary

Create a rule from an allowed-value list.

Parameters

NameTypeDefaultDescription
valuesArrayRequiredValues to inspect or accept as the allowed alternatives.

Return value

Dictionary

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

validate

validate(value: Variant, rule: Dictionary) -> Variant, Err

Validate a value with a rule and return the safe value.

Parameters

NameTypeDefaultDescription
valueVariantRequiredValue to store, serialize, validate or pass to the operation described above.
ruleDictionaryRequiredValidation rule describing the accepted input.

Return value

Variant, Err

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

validate_async

validate_async(value: Variant, rule: Dictionary) -> await Variant, Err

Dispatch nested input validation to a CPU worker.

Parameters

NameTypeDefaultDescription
valueVariantRequiredValue to store, serialize, validate or pass to the operation described above.
ruleDictionaryRequiredValidation rule describing the accepted input.

Return value

await Variant, Err

Returns a Signal. Use await to receive the completion value shown in the signature.

Errors

The result carries a value and an Err. Check the error before using the value; a failure may retain partial progress. In a function returning value, Err, use ? to propagate failure to the caller. The ! operator terminates the program on failure; in serve it fails the current handler.

json_body

json_body(rule: Dictionary, name: String = "body") -> GDWebMiddleware

Create JSON-body validation middleware.

Parameters

NameTypeDefaultDescription
ruleDictionaryRequiredValidation rule describing the accepted input.
nameString"body"Header name or the name used to store a validated value on the request.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

query

query(rule: Dictionary, name: String = "query") -> GDWebMiddleware

Create query validation middleware.

Parameters

NameTypeDefaultDescription
ruleDictionaryRequiredValidation rule describing the accepted input.
nameString"query"Header name or the name used to store a validated value on the request.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.

params

params(rule: Dictionary, name: String = "params") -> GDWebMiddleware

Create route-parameter validation middleware.

Parameters

NameTypeDefaultDescription
ruleDictionaryRequiredValidation rule describing the accepted input.
nameString"params"Header name or the name used to store a validated value on the request.

Return value

GDWebMiddleware

Errors

This call has no Err return slot. Its return type and documented sentinel values determine how to inspect the result.