std/web

Standard Library documentation

Request, response, and routing helpers for ZuzuScript web apps.

Module

Name
std/web
Area
Standard Library
Source
modules/std/web.zzm

NAME

std/web - Request, response, and routing helpers for ZuzuScript web apps.

SYNOPSIS

  from std/web import Request, Response, Routes;

  class Hello {
    static method greet ( req ) {
      return new Response(
        status: 200,
        headers: { "Content-Type": "text/plain; charset=UTF-8" },
        body: [ "Hello ", req.param("name"), "\n" ],
      );
    }
  }

  let routes := new Routes();
  routes.get("/hello/:name").to(
    controller: Hello,
    action: "greet",
  );

  function __request__ ( env ) {
    return routes.dispatch( new Request( env: env ) );
  }

IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and Electron. It is partially supported by zuzu-js in the browser (filesystem backed template rendering fails).

DESCRIPTION

This pure ZuzuScript module provides a small web framework layer over the raw __request__(env) protocol used by ZuzuScript web hosts. It provides request, response, route match, route, and router objects.

EXPORTS

Request

Request wraps the web environment Dict passed to __request__(env).

  • set_session_handler(handler)

    Parameters: handler is a SessionHandler object or null. Returns: the handler. Sets the process-local session handler used by session().

  • get_session_handler()

    Parameters: none. Returns: SessionHandler or null. Returns the process-local session handler.

  • set_route_match(captures, route)

    Parameters: captures is a Dict or null; route is a Route. Returns: Request. Stores the route captures and matched route on the request. This is normally called by Routes.dispatch.

  • env()

    Parameters: none. Returns: Dict. Returns the original request environment.

  • captures()

    Parameters: none. Returns: Dict. Returns captures from the matched route.

  • stash()

    Parameters: none. Returns: Dict. Returns a mutable copy of the matched route captures for per-request application state.

  • route()

    Parameters: none. Returns: Route or null. Returns the route that matched the request.

  • address()

    Parameters: none. Returns: String or null. Returns remote_addr from the environment.

  • remote_host()

    Parameters: none. Returns: String or null. Returns remote_host, falling back to address().

  • request_method()

    Parameters: none. Returns: String. Returns the HTTP request method. This method is not named method() because method is a ZuzuScript keyword.

  • protocol()

    Parameters: none. Returns: String. Returns the HTTP protocol, such as HTTP/1.1.

  • request_uri()

    Parameters: none. Returns: String. Returns the original request URI when available, or reconstructs it from the raw path and query string.

  • path_info()

    Parameters: none. Returns: String. Returns the request path from the environment.

  • path()

    Parameters: none. Returns: String. Returns the request path, normalizing an empty path to /.

  • raw_path()

    Parameters: none. Returns: String. Returns the undecoded path when the host provides one, falling back to path().

  • query_string()

    Parameters: none. Returns: String. Returns the raw query string without a leading question mark.

  • script_name()

    Parameters: none. Returns: String. Returns the mounting path for the application, or an empty string.

  • scheme()

    Parameters: none. Returns: String. Returns the URL scheme, usually http or https.

  • secure()

    Parameters: none. Returns: Boolean. Returns true when the scheme is https.

  • body()

    Parameters: none. Returns: any value or null. Returns the raw body value from the environment.

  • input()

    Parameters: none. Returns: any value or null. Alias for body().

  • content()

    Parameters: none. Returns: any value or null. Alias for body().

  • raw_body()

    Parameters: none. Returns: any value or null. Alias for body().

  • body_text()

    Parameters: none. Returns: String or null. Returns the decoded request body text when the host provides it.

  • user()

    Parameters: none. Returns: String or null. Returns the remote authenticated user from the environment.

  • session()

    Parameters: none. Returns: Session, any value, or null. Returns the request session from the configured SessionHandler. If no handler is configured, it preserves the middleware/host fallback and returns the session environment value.

  • session_options()

    Parameters: none. Returns: any value or null. Returns session options supplied by middleware or the host.

  • logger()

    Parameters: none. Returns: any value or null. Returns a logger object supplied by middleware or the host.

  • headers()

    Parameters: none. Returns: PairList. Returns request headers.

  • header(name)

    Parameters: name is a String. Returns: String or null. Returns the first request header matching name, using case-insensitive matching.

  • content_type()

    Parameters: none. Returns: String or null. Returns the Content-Type request header.

  • content_length()

    Parameters: none. Returns: String or null. Returns the Content-Length request header.

  • content_encoding()

    Parameters: none. Returns: String or null. Returns the Content-Encoding request header.

  • referer()

    Parameters: none. Returns: String or null. Returns the Referer request header.

  • user_agent()

    Parameters: none. Returns: String or null. Returns the User-Agent request header.

  • cookies()

    Parameters: none. Returns: Dict. Parses and returns cookies from the Cookie request header.

  • query_parameters()

    Parameters: none. Returns: PairList. Parses and returns query string parameters. Duplicate names are preserved.

  • body_parameters()

    Parameters: none. Returns: PairList. Parses and returns application/x-www-form-urlencoded body parameters. Duplicate names are preserved.

  • parameters()

    Parameters: none. Returns: PairList. Returns query parameters, body parameters, and route captures in that order.

  • param(name?)

    Parameters: optional name is a String. Returns: String, Array, or null. With a name, returns the first matching merged parameter. With no name, returns the available parameter names.

  • uploads()

    Parameters: none. Returns: PairList. Returns uploaded file entries from the environment, or an empty PairList.

  • upload(name?)

    Parameters: optional name is a String. Returns: an upload value, Array, or null. With a name, returns the first matching upload. With no name, returns the available upload names.

  • uri()

    Parameters: none. Returns: String. Builds the full request URI from the scheme, host, raw path, and query string.

  • base()

    Parameters: none. Returns: String. Builds the application base URI from the scheme, host, and script name.

  • new_response(...args, named)

    Parameters: optional positional values are status, headers, and body; optional named values are status, headers, and body. Returns: Response. Creates a response associated with the request.

Response

Response builds the three-item response array returned by the raw web protocol.

  • status(value?)

    Parameters: optional value is a Number. Returns: Number when reading, or Response when setting. Gets or sets the HTTP status code.

  • code(value?)

    Parameters: optional value is a Number. Returns: Number when reading, or Response when setting. Alias for status().

  • headers(value?)

    Parameters: optional value is a PairList or Dict. Returns: PairList when reading, or Response when setting. Gets or replaces the response headers.

  • header(name, value?)

    Parameters: name is a String; optional value is a String. Returns: String or null when reading, or Response when setting. Gets or replaces a response header using case-insensitive matching.

  • body(value?)

    Parameters: optional value is any response body value. Returns: the current body when reading, or Response when setting. Gets or sets the response body.

  • content(value?)

    Parameters: optional value is any response body value. Returns: the current body when reading, or Response when setting. Alias for body().

  • render(template, data := {})

    Parameters: template is a ZTemplate, ZZTemplate, another object with a process(data) method, or a std/io Path; data is the template data model. Returns: Response. Renders the template with data and sets the response body to the rendered string. Path templates are compiled as ZZTemplate objects and cached with std/cache/lru.

  • content_type(value?)

    Parameters: optional value is a String. Returns: String or null when reading, or Response when setting. Gets or sets the Content-Type response header.

  • render_json(data)

    Parameters: data is any JSON-encodable value. Returns: Response. Encodes data as compact JSON, sets the response body to the JSON text, and sets Content-Type to application/json; charset=UTF-8.

  • session(value?)

    Parameters: optional value is a Session object. Returns: Session or Response. Gets or sets the session object that should contribute a response cookie.

  • content_length(value?)

    Parameters: optional value is a String or Number. Returns: String or null when reading, or Response when setting. Gets or sets the Content-Length response header.

  • content_encoding(value?)

    Parameters: optional value is a String. Returns: String or null when reading, or Response when setting. Gets or sets the Content-Encoding response header.

  • location(value?)

    Parameters: optional value is a String. Returns: String or null when reading, or Response when setting. Gets or sets the Location response header.

  • redirect(url, status := 302)

    Parameters: url is a String; optional status is a Number. Returns: Response. Sets the redirect status code and Location header.

  • cookies()

    Parameters: none. Returns: Dict. Returns the response cookies that have been set with set_cookie().

  • set_cookie(name, value, options := {})

    Parameters: name and value are String; options is a Dict. Returns: Response. Adds a Set-Cookie header and stores the cookie value. Supported options are Path, Domain, Expires, Max-Age, HttpOnly, Secure, and SameSite.

  • finalize()

    Parameters: none. Returns: Array. Finalizes any attached Session, sets its cookie, and returns the raw [ status, headers, body ] response array.

SessionHandler

SessionHandler is the trait enforced by Request.session(). Implementations return an object that does Session.

  • session_for(request)

    Parameters: request is a Request. Returns: Session. Loads or creates the request session.

Session

Session is the trait enforced by Response.finalize().

  • finalize()

    Parameters: none. Returns: Session. Writes pending data, is idempotent, and returns the session object.

  • is_finalized()

    Parameters: none. Returns: Boolean.

  • id()

    Parameters: none. Returns: String.

  • age()

    Parameters: none. Returns: Number.

  • cookie_name()

    Parameters: none. Returns: String.

  • cookie_value()

    Parameters: none. Returns: String.

  • cookie_options()

    Parameters: none. Returns: Dict. Returns options suitable for Response.set_cookie().

RouteMatch

RouteMatch is the match object used internally by the router. It has no public methods. Its fields are route, captures, and position.

Route

Route represents a route node. Applications usually create route nodes through a Routes object.

  • root()

    Parameters: none. Returns: Routes or Route. Returns the root router for this route tree.

  • route_types()

    Parameters: none. Returns: Dict. Returns the named placeholder types available from the root router.

  • parent()

    Parameters: none. Returns: Route or null. Returns the parent route node.

  • children()

    Parameters: none. Returns: Array. Returns child route nodes.

  • pattern()

    Parameters: none. Returns: String. Returns the route pattern for this node.

  • methods(...args)

    Parameters: zero or more String methods, or one Array of method strings. Returns: Array when reading, or Route when setting. Gets or replaces the allowed HTTP methods.

  • name(value?)

    Parameters: optional value is a String. Returns: String when reading, or Route when setting. Gets or sets the route name.

  • has_custom_name()

    Parameters: none. Returns: Boolean. Returns true when name() has explicitly set the route name.

  • inline(value?)

    Parameters: optional value is a truthy or falsey value. Returns: Boolean when reading, or Route when setting. Gets or sets whether the route is an inline bridge route created by under().

  • add_child(route)

    Parameters: route is a Route. Returns: Route. Attaches the route as a child and returns the child route.

  • remove()

    Parameters: none. Returns: Route. Detaches the route from its parent.

  • any(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting any HTTP method.

  • get(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting GET.

  • post(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting POST.

  • put(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting PUT.

  • patch(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting PATCH.

  • delete(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting DELETE.

  • options(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting OPTIONS.

  • head(...args, named)

    Parameters: optional pattern, route name, action, requirements, and named values. Returns: Route. Adds a child route accepting HEAD.

  • under(...args, named)

    Parameters: optional pattern, action, requirements, and named values. Returns: Route. Adds an inline child route that can guard or group nested routes.

  • parse(pattern, named)

    Parameters: pattern is a String; optional named values are route requirements. Returns: Route. Replaces the route pattern and applies requirements.

  • requires(value?, named)

    Parameters: optional value is a Dict, PairList, or flat Array; optional named values are also requirements. Returns: Route. Adds capture, method, host, or header requirements.

  • to(value?, named)

    Parameters: optional value is a controller, Function, Dict, or PairList; named values may include controller and action. Returns: Route. Sets the route target and stores other named values as defaults. String controller targets have the form module/path#ClassName and are lazy loaded with std/internals.load_module.

  • is_endpoint()

    Parameters: none. Returns: Boolean. Returns true when the route has an action or controller target.

  • render(values := {})

    Parameters: values is a Dict or PairList. Returns: String. Builds a path by filling route placeholders with defaults and supplied values.

  • find(wanted)

    Parameters: wanted is a String. Returns: Route or null. Finds a route by name within this route tree.

  • lookup(wanted)

    Parameters: wanted is a String. Returns: Route or null. Alias for find().

  • match(req)

    Parameters: req is a Request. Returns: RouteMatch or null. Finds the first route matching the request path, requirements, and HTTP method.

  • dispatch(request_or_env)

    Parameters: request_or_env is a Request or environment Dict. Returns: Array. Dispatches to the matching action and returns a raw [ status, headers, body ] response array. It returns 404 when no route matches and 405 when only the method is wrong.

Routes

Routes is the root route node. It inherits the Route methods and adds router-wide placeholder type and condition registries.

  • add_type(name, constraint)

    Parameters: name is a String; constraint is a Regexp, Array, Function, or comparable value. Returns: Routes. Adds a named placeholder type for route patterns such as <id:num>.

  • route_types()

    Parameters: none. Returns: Dict. Returns the root router's named placeholder type registry. num is registered by default.

  • add_condition(name, condition)

    Parameters: name is a String; condition is any value. Returns: Routes. Stores a named condition for application use.

COPYRIGHT AND LICENCE

std/web is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under the terms of either the Artistic License 1.0 or the GNU General Public License version 2.