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:
handleris aSessionHandlerobject ornull. Returns: the handler. Sets the process-local session handler used bysession().get_session_handler()Parameters: none. Returns:
SessionHandlerornull. Returns the process-local session handler.set_route_match(captures, route)Parameters:
capturesis aDictornull;routeis aRoute. Returns:Request. Stores the route captures and matched route on the request. This is normally called byRoutes.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:
Routeornull. Returns the route that matched the request.address()Parameters: none. Returns:
Stringornull. Returnsremote_addrfrom the environment.remote_host()Parameters: none. Returns:
Stringornull. Returnsremote_host, falling back toaddress().request_method()Parameters: none. Returns:
String. Returns the HTTP request method. This method is not namedmethod()becausemethodis a ZuzuScript keyword.protocol()Parameters: none. Returns:
String. Returns the HTTP protocol, such asHTTP/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 topath().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, usuallyhttporhttps.secure()Parameters: none. Returns:
Boolean. Returns true when the scheme ishttps.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 forbody().content()Parameters: none. Returns: any value or
null. Alias forbody().raw_body()Parameters: none. Returns: any value or
null. Alias forbody().body_text()Parameters: none. Returns:
Stringornull. Returns the decoded request body text when the host provides it.user()Parameters: none. Returns:
Stringornull. Returns the remote authenticated user from the environment.session()Parameters: none. Returns:
Session, any value, ornull. Returns the request session from the configuredSessionHandler. If no handler is configured, it preserves the middleware/host fallback and returns thesessionenvironment 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:
nameis aString. Returns:Stringornull. Returns the first request header matchingname, using case-insensitive matching.content_type()Parameters: none. Returns:
Stringornull. Returns theContent-Typerequest header.content_length()Parameters: none. Returns:
Stringornull. Returns theContent-Lengthrequest header.content_encoding()Parameters: none. Returns:
Stringornull. Returns theContent-Encodingrequest header.referer()Parameters: none. Returns:
Stringornull. Returns theRefererrequest header.user_agent()Parameters: none. Returns:
Stringornull. Returns theUser-Agentrequest header.cookies()Parameters: none. Returns:
Dict. Parses and returns cookies from theCookierequest 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 returnsapplication/x-www-form-urlencodedbody 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
nameis aString. Returns:String,Array, ornull. 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 emptyPairList.upload(name?)Parameters: optional
nameis aString. Returns: an upload value,Array, ornull. 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, andbody; optional named values arestatus,headers, andbody. 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
valueis aNumber. Returns:Numberwhen reading, orResponsewhen setting. Gets or sets the HTTP status code.code(value?)Parameters: optional
valueis aNumber. Returns:Numberwhen reading, orResponsewhen setting. Alias forstatus().headers(value?)Parameters: optional
valueis aPairListorDict. Returns:PairListwhen reading, orResponsewhen setting. Gets or replaces the response headers.header(name, value?)Parameters:
nameis aString; optionalvalueis aString. Returns:Stringornullwhen reading, orResponsewhen setting. Gets or replaces a response header using case-insensitive matching.body(value?)Parameters: optional
valueis any response body value. Returns: the current body when reading, orResponsewhen setting. Gets or sets the response body.content(value?)Parameters: optional
valueis any response body value. Returns: the current body when reading, orResponsewhen setting. Alias forbody().render(template, data := {})Parameters:
templateis aZTemplate,ZZTemplate, another object with aprocess(data)method, or astd/ioPath;datais the template data model. Returns:Response. Renders the template withdataand sets the response body to the rendered string. Path templates are compiled asZZTemplateobjects and cached withstd/cache/lru.content_type(value?)Parameters: optional
valueis aString. Returns:Stringornullwhen reading, orResponsewhen setting. Gets or sets theContent-Typeresponse header.render_json(data)Parameters:
datais any JSON-encodable value. Returns:Response. Encodesdataas compact JSON, sets the response body to the JSON text, and setsContent-Typetoapplication/json; charset=UTF-8.session(value?)Parameters: optional
valueis aSessionobject. Returns:SessionorResponse. Gets or sets the session object that should contribute a response cookie.content_length(value?)Parameters: optional
valueis aStringorNumber. Returns:Stringornullwhen reading, orResponsewhen setting. Gets or sets theContent-Lengthresponse header.content_encoding(value?)Parameters: optional
valueis aString. Returns:Stringornullwhen reading, orResponsewhen setting. Gets or sets theContent-Encodingresponse header.location(value?)Parameters: optional
valueis aString. Returns:Stringornullwhen reading, orResponsewhen setting. Gets or sets theLocationresponse header.redirect(url, status := 302)Parameters:
urlis aString; optionalstatusis aNumber. Returns:Response. Sets the redirect status code andLocationheader.cookies()Parameters: none. Returns:
Dict. Returns the response cookies that have been set withset_cookie().set_cookie(name, value, options := {})Parameters:
nameandvalueareString;optionsis aDict. Returns:Response. Adds aSet-Cookieheader and stores the cookie value. Supported options arePath,Domain,Expires,Max-Age,HttpOnly,Secure, andSameSite.finalize()Parameters: none. Returns:
Array. Finalizes any attachedSession, 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:
requestis aRequest. 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 forResponse.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:
RoutesorRoute. 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:
Routeornull. 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
Stringmethods, or oneArrayof method strings. Returns:Arraywhen reading, orRoutewhen setting. Gets or replaces the allowed HTTP methods.name(value?)Parameters: optional
valueis aString. Returns:Stringwhen reading, orRoutewhen setting. Gets or sets the route name.has_custom_name()Parameters: none. Returns:
Boolean. Returns true whenname()has explicitly set the route name.inline(value?)Parameters: optional
valueis a truthy or falsey value. Returns:Booleanwhen reading, orRoutewhen setting. Gets or sets whether the route is an inline bridge route created byunder().add_child(route)Parameters:
routeis aRoute. 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 acceptingGET.post(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingPOST.put(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingPUT.patch(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingPATCH.delete(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingDELETE.options(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingOPTIONS.head(...args, named)Parameters: optional pattern, route name, action, requirements, and named values. Returns:
Route. Adds a child route acceptingHEAD.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:
patternis aString; optional named values are route requirements. Returns:Route. Replaces the route pattern and applies requirements.requires(value?, named)Parameters: optional
valueis aDict,PairList, or flatArray; optional named values are also requirements. Returns:Route. Adds capture, method, host, or header requirements.to(value?, named)Parameters: optional
valueis a controller,Function,Dict, orPairList; named values may includecontrollerandaction. Returns:Route. Sets the route target and stores other named values as defaults. String controller targets have the formmodule/path#ClassNameand are lazy loaded withstd/internals.load_module.is_endpoint()Parameters: none. Returns:
Boolean. Returns true when the route has an action or controller target.render(values := {})Parameters:
valuesis aDictorPairList. Returns:String. Builds a path by filling route placeholders with defaults and supplied values.find(wanted)Parameters:
wantedis aString. Returns:Routeornull. Finds a route by name within this route tree.lookup(wanted)Parameters:
wantedis aString. Returns:Routeornull. Alias forfind().match(req)Parameters:
reqis aRequest. Returns:RouteMatchornull. Finds the first route matching the request path, requirements, and HTTP method.dispatch(request_or_env)Parameters:
request_or_envis aRequestor environmentDict. Returns:Array. Dispatches to the matching action and returns a raw[ status, headers, body ]response array. It returns404when no route matches and405when 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:
nameis aString;constraintis aRegexp,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.numis registered by default.add_condition(name, condition)Parameters:
nameis aString;conditionis 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.