rays/worker
Write Cloudflare Workers in Gleam.
The API follows Wisp: requests and responses
are gleam_http types, routing is plain pattern matching, and middleware
is written with use. The difference is that Workers are asynchronous, so
handlers return a Promise(Response).
import gleam/javascript/promise.{type Promise}
import rays/worker.{type Context, type Env, type Request, type Response}
pub fn main() -> worker.Worker {
worker.new(handle_request)
}
fn handle_request(req: Request, _env: Env, _ctx: Context) -> Promise(Response) {
case worker.path_segments(req) {
[] -> worker.ok() |> worker.html_body("<h1>Hello!</h1>") |> promise.resolve
_ -> promise.resolve(worker.not_found())
}
}
The worker is exported to Cloudflare from a small entry module:
// index.mts
import { main } from "./build/dev/javascript/my_app/my_app.mjs";
export default main();
Types
The body of an HTTP response.
The body is not sent for statuses that cannot have one (101, 204, 205, and 304).
pub type Body {
Text(String)
Bytes(BitArray)
Stream(ReadableStream)
Empty
}
Constructors
-
Text(String)A body of UTF-8 text.
-
Bytes(BitArray)A body of binary data. If it is not a whole number of bytes, a 500 response is sent instead.
-
Stream(ReadableStream)A streaming body, passed through to the client without buffering.
-
EmptyNo body.
An error that can occur when reading the body of an incoming request, or
of a response received with rays/fetch.
pub type BodyError {
BodyAlreadyRead
BodyReadFailed(reason: String)
InvalidUtf8
}
Constructors
-
BodyAlreadyReadThe body has already been read by an earlier call.
-
BodyReadFailed(reason: String)The body could not be read from the client, for example because the connection was lost. The reason is the runtime’s error message.
-
InvalidUtf8The body was read but is not valid UTF-8.
The Worker’s execution context, used to extend the lifetime of the
request with wait_until and to control failure behaviour with
pass_through_on_exception.
pub type Context
The bindings configured for the Worker: environment variables, secrets, and resources such as KV namespaces or D1 databases.
pub type Env
A function that handles an incoming HTTP request.
pub type Handler =
fn(request.Request(RequestBody), Env, Context) -> promise.Promise(
response.Response(Body),
)
A streaming body, such as an incoming request body or the body of a
response from fetch.
pub type ReadableStream
An incoming HTTP request.
pub type Request =
request.Request(RequestBody)
The body of an incoming request.
The body is not read until one of the body reading functions such as
read_body_bits or require_string_body is called. A body can only be
read once.
Internally this holds the whole Fetch API Request, because Cloudflare’s
cf properties are read from it too. The method, URL, and headers are
only taken from the Gleam request record.
pub opaque type RequestBody
An HTTP response.
pub type Response =
response.Response(Body)
A Cloudflare Worker, ready to be exported as the default export of the Worker’s entry module.
At runtime this is the ExportedHandler object Cloudflare expects, with a
fetch method, so a JavaScript entry module can export default main().
It also has a Symbol.for("rays.worker") property set to true, which
handler() from the @rays/core npm package checks for. Both are
stable parts of the runtime shape.
pub type Worker
Values
pub fn bad_request(detail: String) -> response.Response(Body)
A 400: Bad request response. The detail is included in the body if it is not empty.
pub fn bit_array_body(
response: response.Response(a),
content: BitArray,
) -> response.Response(Body)
Set the body of a response to the given binary data. The content type is not changed.
pub fn body_stream(
request: request.Request(RequestBody),
) -> Result(ReadableStream, BodyError)
Get the request body as a stream, without reading it into memory. A request without a body gives an empty stream.
Returns BodyAlreadyRead if the body has already been read.
pub fn cf_properties(
request: request.Request(RequestBody),
) -> Result(dynamic.Dynamic, Nil)
Get Cloudflare’s cf properties for the request, such as the client’s
country, the data centre that handled the request, and TLS details.
Returns an error when running outside Cloudflare, for example in tests.
pub fn content_too_large() -> response.Response(Body)
A 413: Content too large response.
pub fn env_binding(
env: Env,
name: String,
) -> Result(dynamic.Dynamic, Nil)
Get any binding from the Worker’s environment as a dynamic value.
Returns an error if there is no binding with that name, or if its value
is null.
This is an escape hatch for bindings that rays does not yet provide
typed APIs for.
pub fn env_var(env: Env, name: String) -> Result(String, Nil)
Get a string environment variable or secret from the Worker’s bindings.
Returns an error if there is no binding with that name, or if the binding is not a string (for example a KV namespace).
Examples
case worker.env_var(env, "API_TOKEN") {
Ok(token) -> todo
Error(_) -> worker.internal_server_error() |> promise.resolve
}
pub fn get_query(
request: request.Request(RequestBody),
) -> List(#(String, String))
Get the query parameters of the request. Returns an empty list if the query string is missing or malformed.
pub fn html_body(
response: response.Response(a),
html: String,
) -> response.Response(Body)
Set the body of a response to the given HTML, and set the content type to
text/html.
pub fn html_response(
html: String,
status: Int,
) -> response.Response(Body)
Create an HTML response with the given status code.
pub fn internal_server_error() -> response.Response(Body)
A 500: Internal server error response.
pub fn json_body(
response: response.Response(a),
data: json.Json,
) -> response.Response(Body)
Set the body of a response to the given JSON, and set the content type to
application/json.
pub fn json_response(
data: json.Json,
status: Int,
) -> response.Response(Body)
Create a JSON response with the given status code.
Examples
json.object([#("name", json.string("Joe"))])
|> worker.json_response(201)
pub fn method_not_allowed(
allowed methods: List(http.Method),
) -> response.Response(Body)
A 405: Method not allowed response, listing the allowed methods.
pub fn new(
handler: fn(request.Request(RequestBody), Env, Context) -> promise.Promise(
response.Response(Body),
),
) -> Worker
Create a Worker that handles HTTP requests with the given handler.
Examples
pub fn main() -> worker.Worker {
worker.new(handle_request)
}
With tracing
enabled, the Worker also adds to the span Cloudflare records for each
request, as described in rays/observability/trace: it names the span after the
request’s route, such as GET /users/:id, records the response’s status,
marks 5xx responses as failed, and records where a panic happened.
pub fn pass_through_on_exception(ctx: Context) -> Nil
If the Worker throws an unhandled exception, forward the request to the origin server instead of returning an error page.
pub fn path_segments(
request: request.Request(RequestBody),
) -> List(String)
Split the request path into its segments.
Examples
// GET /users/123
worker.path_segments(request)
// -> ["users", "123"]
pub fn permanent_redirect(
to url: String,
) -> response.Response(Body)
A 308: Permanent redirect response.
pub fn read_body_bits(
request: request.Request(RequestBody),
) -> promise.Promise(Result(BitArray, BodyError))
Read the entire request body as a bit array. A request without a body gives an empty bit array.
Returns BodyAlreadyRead if the body has already been read, and
BodyReadFailed if it could not be read.
pub fn read_body_string(
request: request.Request(RequestBody),
) -> promise.Promise(Result(String, BodyError))
Read the entire request body as a UTF-8 string.
Returns the same errors as read_body_bits, and InvalidUtf8 if the
body is not valid UTF-8.
pub fn redirect(to url: String) -> response.Response(Body)
A 303: See other response, redirecting the client to the given URL with a GET request.
pub fn require_bit_array_body(
request: request.Request(RequestBody),
next: fn(BitArray) -> promise.Promise(response.Response(Body)),
) -> promise.Promise(response.Response(Body))
Read the request body as a bit array.
Responds with 400: Bad request if the body cannot be read.
pub fn require_content_type(
request: request.Request(body),
expected: String,
next: fn() -> promise.Promise(response.Response(Body)),
) -> promise.Promise(response.Response(Body))
Ensure the request has the given media type, responding with 415: Unsupported media type otherwise.
The comparison ignores case and parameters such as ; charset=utf-8, so
"application/json" matches Application/JSON; charset=utf-8.
pub fn require_form(
request: request.Request(RequestBody),
next: fn(List(#(String, String))) -> promise.Promise(
response.Response(Body),
),
) -> promise.Promise(response.Response(Body))
Read a application/x-www-form-urlencoded request body as a list of
key-value pairs, sorted by key.
Responds with 415: Unsupported media type for any other content type, and with 400: Bad request if the body is not a valid form encoding.
Multipart form bodies are not yet supported.
pub fn require_json(
request: request.Request(RequestBody),
next: fn(dynamic.Dynamic) -> promise.Promise(
response.Response(Body),
),
) -> promise.Promise(response.Response(Body))
Read the request body as JSON, returning a dynamic value to be decoded.
Responds with 415: Unsupported media type if the content type is not
application/json, and with 400: Bad request if the body is not valid
JSON.
Examples
use value <- worker.require_json(req)
case decode.run(value, person_decoder()) {
Ok(person) -> todo
Error(_) -> worker.unprocessable_content() |> promise.resolve
}
pub fn require_method(
request: request.Request(body),
method: http.Method,
next: fn() -> promise.Promise(response.Response(Body)),
) -> promise.Promise(response.Response(Body))
Ensure the request has the given method, responding with 405: Method not allowed otherwise.
Examples
use <- worker.require_method(req, http.Post)
pub fn require_string_body(
request: request.Request(RequestBody),
next: fn(String) -> promise.Promise(response.Response(Body)),
) -> promise.Promise(response.Response(Body))
Read the request body as a UTF-8 string.
Responds with 400: Bad request if the body cannot be read or is not valid UTF-8.
Examples
use body <- worker.require_string_body(req)
pub fn response(status: Int) -> response.Response(Body)
Create a response with the given status code and no body.
pub fn set_body(
response: response.Response(a),
body: Body,
) -> response.Response(Body)
Set the body of a response.
pub fn set_header(
response: response.Response(a),
name: String,
value: String,
) -> response.Response(a)
Set a header on a response, replacing any existing header with the same name.
pub fn stream_body(
response: response.Response(a),
stream: ReadableStream,
) -> response.Response(Body)
Set the body of a response to a stream. The content type is not changed.
pub fn string_body(
response: response.Response(a),
content: String,
) -> response.Response(Body)
Set the body of a response to the given text. The content type is not changed.
pub fn unprocessable_content() -> response.Response(Body)
A 422: Unprocessable content response.
pub fn unsupported_media_type(
accept acceptable: List(String),
) -> response.Response(Body)
A 415: Unsupported media type response, listing the accepted media types.
pub fn wait_until(
ctx: Context,
promise: promise.Promise(a),
) -> Nil
Extend the lifetime of the Worker until the given promise settles, without delaying the response. Useful for logging, analytics, or cache writes.