Skip to content

web ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793849272/FIN+5.3.1+web 中文整理基于 FIN 5.3.1

导读: 用于处理 HTTP 请求的标准 weblet API

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • mixins
  • classes
  • docs
  • Overview
  • WebClient
  • Weblets
  • WebReq
  • WebRes
  • WebSessions
  • WebMods
  • Expect Continue
  • Slot Details
    • domain
    • fromStr
    • httpOnly
    • make
    • maxAge
    • name
    • path
    • sameSite
    • secure
    • toStr
    • val
    • makeFiles
    • onGet
    • pack
    • toAppCssFiles
    • toAppJsFiles
    • toEtcJsFiles
    • toIndexPropsJsFile
    • toLocaleJsFile
    • toMimeJsFile
    • toPodCssFiles
    • toPodJsFile
    • toPodJsFiles
    • toPodJsMapFile
    • toTimezonesJsFile
    • toUnitsJsFile
    • checkNotModified
    • checkUnderDir
    • etag
    • extraResHeaders
    • file
    • modified
    • onService
    • authBasic
    • close
    • cookies
    • followRedirects
    • getBuf
    • getIn
    • getStr
    • isConnected
    • postBuf
    • postFile
    • postForm
    • postStr
    • proxy
    • readRes
    • reqHeaders
    • reqMethod
    • reqOut
    • reqUri

API 正文(英文) ​

docs ​

Overview ​

The web pod defines the standard APIs used to handle both client and server side HTTP requests.

Client side HTTP requests:

  • WebClient: manages client side of the HTTP protocol

Server side web APIs are organized into the primary classes:

  • WebReq: models an incoming web request such as the method, uri, request headers, and input stream.
  • WebRes: models the outgoing web response such as the status code, response headers, and output stream.
  • Weblet: an entity which processes a web request.
  • WebMod: a web module which may be composed with other modules to build up a web solution.

WebClient ​

The WebClient class is used to manage client side HTTP requests and responses. The basic lifecycle of WebClient:

  1. configure request fields such as reqUri, reqMethod, and reqHeaders
  2. send request headers via writeReq
  3. optionally write request body via reqOut
  4. read response status and headers via readRes
  5. process response fields such as resCode and resHeaders
  6. optionally read response body via resIn

Using the low level methods writeReq and readRes enables HTTP pipelining (multiple requests and responses on the same TCP socket connection). There are also a series of convenience methods which make common cases easier.

See examples for sample code.

Weblets ​

Pretty much anything that touches a HTTP request should be implement Weblet. The lifecycle of a Weblet is quite simple:

  • all web requests are guaranteed to be called on their own actor/thread with the actor locals "web.req" and "web.res"
  • req and res: the current actor's WebReq and WebRes are available with these methods - so there no need to pass the request and response around
  • onService: the onService method can be overridden directly to handle the request, or the default implementation will route to the doGet, doPost, etc methods

WebReq ​

The WebReq class models the request side of a HTTP request. Common methods you will use include:

  • method: HTTP method such as "GET" or "POST"
  • uri: the request URI parsed into a Uri which allows you access the parsed path and query segments.
  • mod: web module currently responsible for request
  • modBase: URI used to route to current module
  • modRel: module relative URI used for module internal processing
  • headers: a case insensitive Str:Str map of the request HTTP headers
  • in: access to the raw input stream of the request
  • form: access to the parsed form data
  • cookies: a Str:Str map of cookies
  • session: a Str:Obj map used to stash stuff for the browser "connection" between HTTP requests
  • stash: a Str:Obj map used to stash stuff only for the life of request

WebRes ​

The WebRes class models the response side of a HTTP request. A WebRes has the following lifecycle:

  • Uncommitted: at this point nothing has been written back on the TCP socket and statusCode, headers, and cookies are still configurable
  • Committed: at this point the HTTP response headers have been written, and you can write the response content via the out stream. Once a response is committed, attempts to access statusCode, headers, cookies, redirect, or sendErr will raise an exception
  • Done: at this point the response is complete - for example once the redirect or sendErr method is called, the response is done

Common methods you will use include:

  • statusCode: sets the HTTP status code - must be set before commit
  • headers: a Str:Str map of HTTP headers - must be set before commit
  • cookies: used to set the cookie header - must be set before commit
  • out: the output stream for writing the content - first call commits the response
  • isCommitted: check commit state
  • isDone: check done state
  • sendErr: used to send an error status code
  • redirect: used to send a redirect status code

WebRes is a fairly low level API which requires the commit state model to avoid buffering the content.

WebSessions ​

The WebSession class models the client session which allows you to persist state between HTTP requests. WebSessions in Fantom are cookie based using the cookie name "fanws". The default session implementation stores sessions in memory for up to 24 hours, then clears them from the cache - session state is not persisted between VM restarts.

WebSession provides a Str:Obj? map to store arbitrary name/value pairs. You can use the map, get, or set methods to manage session state. You can use delete to explicitly delete the session cookie and server side state. The values stored in a WebSession should always be serializable objects.

WebSessions are created and accessed via the WebReq.session method. The first time a session is accessed it sets the cookie header in the response - therefore sessions should always be accessed before the response is committed. Deleting a session also requires setting the cookie header and must done before the response is committed.

Example of storing a counter in a session:

override Void doGet()
{
  Int count := req.session.get("counter", 0)
  req.session["counter"] = count + 1

  res.headers["Content-Type"] = "text/plain"
  res.statusCode = 200
  res.out.printLine("session counter=$count")
}

WebMods ​

The WebMod class is the base class for plugging in web server modules. WebMods are immutable Weblets which may be composed together to build higher level modules or to configure the entire web server.

During processing of a given web request, there is always exactly one WebMod responsible for the request which is available via the WebReq.mod method. The URI used to route to the module is accessed by WebReq.modBase, and the remainder of the URI which is internal to the module via WebReq.modRel. Using these methods you can write modules which can be freely plugged anywhere into a server's URI namespace.

WebMods receive the onStart and onStop callbacks when the web server is started and stopped. These callbacks can be used to perform initialization and cleanup such as managing actors.

The webmod pod includes a library of modules which are designed to handle common tasks such publishing static files, routing, and pipelining.

Expect Continue ​

Using "Expect: 100-continue" allows the server to fail-fast and report an error to the client before the client sends the request body. This technique is often used before posting large files to verify preconditions.

The WebClient API does not provide automatic support for using the Expect header. You must manually handle flow control yourself. Here is a simple example showing how to post a file using the Expect header:

c := WebClient(`http://example.com/post-file`)
c.reqMethod = "POST"
c.reqHeaders["Content-Type"] = file.mimeType.toStr
c.reqHeaders["Content-Length"] = file.size.toStr
c.reqHeaders["Expect"] = "100-continue"
c.writeReq
c.readRes
if (c.resCode != 100) throw IOErr("Expecting 100, not $c.resCode")
file.in.pipe(c.reqOut, file.size)
c.reqOut.close
c.readRes
if (c.resCode != 200) throw IOErr("Expecting 200, not $c.resCode")

Server side processing of the Expect header is automatic. When a Weblet acquires the WebReq.in stream for the first time, the request is checked for the "Expect: 100-continue" header and if specified, then a 100 Continue is automatically sent.


Cookie ​

@Js const class Cookie : Obj

Cookie models an HTTP cookie used to pass data between the server and user agent as defined by RFC 6265.

See WebReq.cookies and WebRes.cookies.

Constructors

fromStrParse a HTTP cookie header name/value pair.
makeConstruct with name and value.

Fields

domainSpecifies the domain for which the cookie is valid.
httpOnlyIf true, then the cookie is not available to JavaScript.
maxAgeDefines the lifetime of the cookie, after the the max-age elapses the client should discard the cookie.
nameName of the cookie.
pathSpecifies the subset of URLs to which the cookie applies.
sameSiteIf this value is non-null, then we add the SameSite attribute to the cookie.
secureIf true, then the client only sends this cookie using a secure protocol such as HTTPS.
valValue string of the cookie.

Methods

toStrReturn the cookie formatted as an Set-Cookie HTTP header.

Slot Details ​


domain ​

const Str? domain

Specifies the domain for which the cookie is valid. An explicit domain must always start with a dot. If null (the default) then the cookie only applies to the server which set it.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Parse a HTTP cookie header name/value pair. The parsing of the name-value pair is done according to the algorithm outlined in § 5.2 of the RFC.

Throw ParseErr or return null if not formatted correctly.


httpOnly ​

const Bool httpOnly := true

If true, then the cookie is not available to JavaScript. Defaults to true.


make ​

new make(Str name, Str val, |This|? f := null)

Construct with name and value. The name must be a valid HTTP token and must not start with "$" (see WebUtil.isToken). The value string must be an ASCII string within the inclusive range of 0x20 and 0x7e (see WebUtil.toQuotedStr) with the exception of the semicolon.

Fantom cookies will use quoted string values, however some browsers such as IE won't parse a quoted string with semicolons correctly, so we make semicolons illegal. If you have a value which might include non-ASCII characters or semicolons, then consider encoding using something like Base64:

// write response
res.cookies.add(Cookie("baz", val.toBuf.toBase64))

// read from request
val := Buf.fromBase64(req.cookies.get("baz", "")).readAllStr

maxAge ​

const Duration? maxAge

Defines the lifetime of the cookie, after the the max-age elapses the client should discard the cookie. The duration is floored to seconds (fractional seconds are truncated). If maxAge is null (the default) then the cookie persists until the client is shutdown. If zero is specified, the cookie is discarded immediately. Note that many browsers still don't recognize max-age, so setting max-age also always includes an expires attribute.


name ​

const Str name

Name of the cookie.


path ​

const Str? path := "/"

Specifies the subset of URLs to which the cookie applies. If set to "/" (the default), then the cookie applies to all paths. If the path is null, it as assumed to be the same path as the document being described by the header which contains the cookie.


sameSite ​

const Str? sameSite := "strict"

If this value is non-null, then we add the SameSite attribute to the cookie. Valid values are

  • lax
  • strict By default we set the attribute to strict

secure ​

const Bool secure := false

If true, then the client only sends this cookie using a secure protocol such as HTTPS. Defaults to false.


toStr ​

virtual override Str toStr()

Return the cookie formatted as an Set-Cookie HTTP header.


val ​

const Str val

Value string of the cookie.


FilePack ​

const class FilePack : Obj, Weblet

FilePack is an in-memory cache of multiple text files to service static resources via HTTP. It takes one or more text files and creates one compound file. The result is stored in RAM using GZIP compression. Or you can use the pack utility method to store the result to your own files/buffers.

The onGet method is used to service GET requests for the bundle. The Content-Type header is set based on file extension of files bundled. It also implictly supports ETag/Last-Modified for 304 optimization.

The core factory is the makeFiles constructor. A suite of utility methods is provided for standard bundling of Fantom JavaScrit and CSS files.

Constructors

makeFilesConstruct a bundle for the given list of text files

Methods

onGetService an HTTP GET request for this bundle file
packPack multiple text files together and write to the given output stream.
toAppCssFilesGiven a set of pods return a list of CSS files that form a complete Fantom application
toAppJsFilesGiven a set of pods return a list of JavaScript files that form a complete Fantom application
toEtcJsFilesReturn the required sys etc files
toIndexPropsJsFileCompile the indexed props database into a JavaScript file "index-props.js"
toLocaleJsFileCompile the locale props into a JavaScript file "{locale}.js"
toMimeJsFileCompile the mime type database into a Javascript file "mime.js"
toPodCssFilesMap a set of pods to "/res/css/{name}.css" CSS files.
toPodJsFileGet the standard pod JavaScript file or null if no JS code.
toPodJsFilesMap a set of pods to "/{name}.js" JavaScript files.
toPodJsMapFileCompile a list of pod JavaScript files into a single unified source map file.
toTimezonesJsFileCompile the timezone database into a JavaScript file "tz.js"
toUnitsJsFileCompile the unit database into a JavaScript file "unit.js"

Slot Details ​


makeFiles ​

static new makeFiles(File[] files, MimeType? mimeType := null)

Construct a bundle for the given list of text files


onGet ​

virtual override Void onGet()

Service an HTTP GET request for this bundle file


pack ​

static OutStream pack(File[] files, OutStream out)

Pack multiple text files together and write to the given output stream. A trailing newline is automatically added if the file is missing one. Empty files are skipped. The stream is not closed. Return the given out stream.


toAppCssFiles ​

static File[] toAppCssFiles(Pod[] pods)

Given a set of pods return a list of CSS files that form a complete Fantom application:

  • flatten the pods using Pod.flattenDepends
  • order them by dependencies using Pod.orderByDepends
  • return toPodCssFiles

toAppJsFiles ​

static File[] toAppJsFiles(Pod[] pods)

Given a set of pods return a list of JavaScript files that form a complete Fantom application:

  • flatten the pods using Pod.flattenDepends
  • order them by dependencies using Pod.orderByDepends
  • insert toEtcJsFiles immediately after "sys.js"

toEtcJsFiles ​

static File[] toEtcJsFiles()

Return the required sys etc files:

  • add toMimeJsFile
  • add toUnitsJsFile
  • add toIndexPropsJsFile

toIndexPropsJsFile ​

static File toIndexPropsJsFile(Pod[] pods := Pod.list())

Compile the indexed props database into a JavaScript file "index-props.js"


toLocaleJsFile ​

static File toLocaleJsFile(Locale locale, Pod[] pods := Pod.list())

Compile the locale props into a JavaScript file "{locale}.js"


toMimeJsFile ​

static File toMimeJsFile()

Compile the mime type database into a Javascript file "mime.js"


toPodCssFiles ​

static File[] toPodCssFiles(Pod[] pods)

Map a set of pods to "/res/css/{name}.css" CSS files. Ignore pods that are missing a CSS file. This method does not flatten/order the pods.


toPodJsFile ​

static File? toPodJsFile(Pod pod)

Get the standard pod JavaScript file or null if no JS code. The standard location used by the Fantom JS compiler is "/{pod-name}.js"


toPodJsFiles ​

static File[] toPodJsFiles(Pod[] pods)

Map a set of pods to "/{name}.js" JavaScript files. Ignore pods that are missing a JavaScript file. This method does not flatten/order the pods.


toPodJsMapFile ​

static File toPodJsMapFile(File[] files, [Str:Obj]? options := null)

Compile a list of pod JavaScript files into a single unified source map file. The list of files passed to this method should match exactly the list of files used to create the corresponding JavaScript FilePack. If the file is the standard pod JS file, then we will include an offset version of "{pod}.js.map" generated by the JavaScript compiler. Otherwise if the file is another JavaScript file (such as units.js) then we just add the appropiate offset.

The sourceRoot option may be passed in to replace "/dev/{podName}" as the root URI used to fetch source files from the server.


toTimezonesJsFile ​

@Deprecated { msg=... } static File toTimezonesJsFile()

Compile the timezone database into a JavaScript file "tz.js"


toUnitsJsFile ​

static File toUnitsJsFile()

Compile the unit database into a JavaScript file "unit.js"


FileWeblet ​

class FileWeblet : Obj, Weblet

FileWeblet is used to service an HTTP request on a File. It handles all the dirty details for cache control, compression, modification time, ETags, etc.

Default implementation uses gzip encoding if gzip is supported by the client and the file's MIME type has a "text" media type.

Current implementation supports ETags and Modification time for cache validation. It does not specify any cache control directives.

Constructors

makeConstructor with file to service.

Fields

extraResHeadersExtra response headers to add for all 3xx and 2xx responses
fileThe file being serviced by this FileWeblet.

Methods

checkNotModifiedCheck if the request passed headers indicating it has cached version of the file.
checkUnderDirChecks if the file being served is under the given directory.
etagCompute the ETag for the file being serviced which uniquely identifies the file version.
modifiedGet the modified time of the file floored to 1 second which is the most precise that HTTP can deal with.
onGetHandle GET request for the file.
onService

Slot Details ​


checkNotModified ​

protected virtual Bool checkNotModified()

Check if the request passed headers indicating it has cached version of the file. If the file has not been modified, then service the request as 304 and return true. This method supports ETag "If-None-Match" and "If-Modified-Since" modification time.


checkUnderDir ​

This checkUnderDir(File dir)

Checks if the file being served is under the given directory. If it is not, a 404 response is immediately sent, short-circuiting any further attempts to serve the file.

FileWeblet(file).checkUnderDir(dir).onService

etag ​

virtual Str etag()

Compute the ETag for the file being serviced which uniquely identifies the file version. The default implementation is a hash of the modified time and the file size. The result of this method must conform to the ETag syntax and be wrapped in quotes.


extraResHeaders ​

[Str:Str]? extraResHeaders

Extra response headers to add for all 3xx and 2xx responses


file ​

const File file

The file being serviced by this FileWeblet.


make ​

new make(File file)

Constructor with file to service.


modified ​

virtual DateTime modified()

Get the modified time of the file floored to 1 second which is the most precise that HTTP can deal with.


onGet ​

virtual override Void onGet()

Handle GET request for the file.


onService ​

virtual override Void onService()


WebClient ​

class WebClient : Obj

The WebClient class is used to manage client side HTTP requests and responses. The basic lifecycle of WebClient:

  1. configure request fields such as reqUri, reqMethod, and reqHeaders
  2. send request headers via writeReq
  3. optionally write request body via reqOut
  4. read response status and headers via readRes
  5. process response fields such as resCode and resHeaders
  6. optionally read response body via resIn

Using the low level methods writeReq and readRes enables HTTP pipelining (multiple requests and responses on the same TCP socket connection). There are also a series of convenience methods which make common cases easier.

See pod doc and examples.

Constructors

makeConstruct with optional request URI.

Fields

cookiesCookies to pass for "Cookie" request header.
followRedirectsWhen set to true a 3xx response with a Location header will automatically update the reqUri field and retry the request using the alternate URI.
proxyIf non-null, then all requests are routed through this proxy address (host and port).
reqHeadersThe HTTP headers to use for the next request.
reqMethodThe HTTP method for the request.
reqUriThe absolute URI of request.
reqVersionHTTP version to use for request must be 1.0 or 1.1.
resCodeHTTP status code returned by response.
resHeadersHTTP headers returned by response.
resPhraseHTTP status reason phrase returned by response.
resVersionHTTP version returned by response.
socketConfigThe SocketConfig to use for creating sockets

Methods

authBasicAuthenticate request using HTTP Basic with given username and password.
closeClose the HTTP request and the underlying socket.
getBufMake a GET request and return the response content as an in-memory byte buffer.
getInMake a GET request and return the input stream to the response or throw IOErr if response is not 200.
getStrMake a GET request and return the response content as an in-memory string.
isConnectedReturn if this web client is currently connected to the remote host.
postBufConvenience for writeBuf("POST", content).readRes
postFileConvenience for writeFile("POST", file).readRes
postFormConvenience for writeForm("POST", form).readRes
postStrConvenience for writeStr("POST", content).readRes
readResRead the response status line and response headers.
reqOutGet the output stream used to write the request body.
resBufReturn the entire response back as an in-memory byte buffer.
resHeaderGet a response header.
resInInput stream to read response content.
resStrReturn the entire response back as an in-memory string.
socketOptions
writeBufWrite a binary buffer using the given HTTP method to the URI.
writeFileWrite a file using the given HTTP method to the URI.
writeFormMake a request with the given HTTP method to the URI with the given form data.
writeReqWrite the request line and request headers.
writeStrMake a request with the given HTTP method to the URI using UTF-8 encoding of given string.

Slot Details ​


authBasic ​

This authBasic(Str username, Str password)

Authenticate request using HTTP Basic with given username and password.


close ​

This close()

Close the HTTP request and the underlying socket. Return this.


cookies ​

Cookie[] cookies := Cookie#.emptyList

Cookies to pass for "Cookie" request header. If set to an empty list then the "Cookie" request header is removed. After a request has been completed if the "Set-Cookie" response header specified one or more cookies then this field is automatically updated with the server specified cookies.


followRedirects ​

Bool followRedirects := true

When set to true a 3xx response with a Location header will automatically update the reqUri field and retry the request using the alternate URI. Redirects are not followed if the request has a content body.


getBuf ​

Buf getBuf()

Make a GET request and return the response content as an in-memory byte buffer. The web client is automatically closed. Throw IOErr is response is not 200.


getIn ​

InStream getIn()

Make a GET request and return the input stream to the response or throw IOErr if response is not 200. It is the caller's responsibility to close this web client.


getStr ​

Str getStr()

Make a GET request and return the response content as an in-memory string. The web client is automatically closed. Throw IOErr is response is not 200.


isConnected ​

Bool isConnected()

Return if this web client is currently connected to the remote host.


make ​

new make(Uri? reqUri := null)

Construct with optional request URI.


postBuf ​

This postBuf(Buf buf)

Convenience for writeBuf("POST", content).readRes


postFile ​

This postFile(File file)

Convenience for writeFile("POST", file).readRes


postForm ​

This postForm(Str:Str form)

Convenience for writeForm("POST", form).readRes


postStr ​

This postStr(Str content)

Convenience for writeStr("POST", content).readRes


proxy ​

Uri? proxy := proxyDef

If non-null, then all requests are routed through this proxy address (host and port). Default is configured in "etc/web/config.props" with the key "proxy". Proxy exceptions can be configured with the "proxy.exceptions" config key as comma separated list of Regex globs.


readRes ​

This readRes()

Read the response status line and response headers. This method may be called after the request has been written via writeReq and reqOut. Once this method completes the response status and headers are available. If there is a response body, it is available for reading via resIn. Throw IOErr if there is a network or protocol error. Return this.


reqHeaders ​

Str:Str reqHeaders := ...

The HTTP headers to use for the next request. This map uses case insensitive keys. The "Host" header is implicitly defined by reqUri and must not be defined in this map.


reqMethod ​

Str reqMethod := "GET"

The HTTP method for the request. Defaults to "GET".


reqOut ​

OutStream reqOut()

Get the output stream used to write the request body. This stream is only available if the request headers included a "Content-Type" header. If an explicit "Content-Length" was specified then this is a fixed length output stream, otherwise the request is automatically configured to use a chunked transfer encoding. This stream should be closed once the content has been fully written.


reqUri ​

Uri reqUri := ``

The absolute URI of request.


reqVersion ​

Version reqVersion := ver11

HTTP version to use for request must be 1.0 or 1.1. Default is 1.1.


resBuf ​

Buf resBuf()

Return the entire response back as an in-memory byte buffer. Convenience for resIn.readAllBuf.


resCode ​

Int resCode

HTTP status code returned by response.


resHeader ​

Str? resHeader(Str key, Bool checked := true)

Get a response header. If not found and checked is false then return true, otherwise throw Err.


resHeaders ​

Str:Str resHeaders := noHeaders

HTTP headers returned by response.


resIn ​

InStream resIn()

Input stream to read response content. The input stream will correctly handle end of stream when the content has been fully read. If the "Content-Length" header was specified the end of stream is based on the fixed number of bytes. If the "Transfer-Encoding" header defines a chunked encoding, then chunks are automatically handled. If the response has no content body, then throw IOErr.

The response input stream is automatically configured with the correct character encoding if one is specified in the "Content-Type" response header.

Also see convenience methods: resStr and resBuf.


resPhrase ​

Str resPhrase := ""

HTTP status reason phrase returned by response.


resStr ​

Str resStr()

Return the entire response back as an in-memory string. Convenience for resIn.readAllStr.


resVersion ​

Version resVersion := ver11

HTTP version returned by response.


socketConfig ​

SocketConfig socketConfig := SocketConfig.cur

The SocketConfig to use for creating sockets


socketOptions ​

@Deprecated { msg=... } SocketOptions socketOptions()


writeBuf ​

This writeBuf(Str method, Buf content)

Write a binary buffer using the given HTTP method to the URI. If Content-Type header is not already set, then it is set as ""application/octet-stream". This method does not support the "Expect" header


writeFile ​

This writeFile(Str method, File file)

Write a file using the given HTTP method to the URI. If Content-Type header is not already set, then it is set from the file extension's MIME type. This method does not support the "Expect" header (it writes full file before reading response). Should primarily be used for "POST" and "PATCH" requests.


writeForm ​

This writeForm(Str method, Str:Str form)

Make a request with the given HTTP method to the URI with the given form data. Set the Content-Type to application/x-www-form-urlencoded. This method does not support the "Expect" header (it writes all form data before reading response). Should primarily be used for POST and PATCH requests.


writeReq ​

This writeReq()

Write the request line and request headers. Once this method completes the request body may be written via reqOut, or the response may be immediately read via readRes. Throw IOErr if there is a network or protocol error. Return this.


writeStr ​

This writeStr(Str method, Str content)

Make a request with the given HTTP method to the URI using UTF-8 encoding of given string. If Content-Type is not already set, then set it to "text/plain; charset=utf-8". This method does not support the "Expect" header (it writes full string before reading response). Should primarily be used for "POST" and "PATCH" requests.


WebMod ​

abstract const class WebMod : Obj, Weblet

WebMod defines a web modules which is plugged into a web server's URI namespace to service web requests.

See pod doc.

Methods

onStartInitialization callback when web server is started.
onStopCleanup callback when web server is stoppped.

Slot Details ​


onStart ​

virtual Void onStart()

Initialization callback when web server is started.


onStop ​

virtual Void onStop()

Cleanup callback when web server is stoppped.


WebOutStream ​

@Js class WebOutStream : OutStream

WebOutStream provides methods for generating XML and XHTML content.

Constructors

makeConstruct a WebOutStream that wraps the given OutStream.

Methods

aStart a <a> tag.
aEndEnd a <a> tag.
articleStart a <article> tag.
articleEndEnd a <article> tag.
asideStart a <aside> tag.
asideEndEnd a <aside> tag.
atomWrite a complete <link> tag for an Atom feed resource.
bStart a <b> tag.
bEndEnd a <b> tag.
bodyStart a <body> tag.
bodyEndEnd a <body> tag.
brWrite out a complete tag.
buttonConvenience for input("type='button'" + attrs).
checkboxConvenience for input("type='checkbox'" + attrs)
codeStart a <code> tag.
codeEndEnd a <code> tag.
ddStart a <dd> tag.
ddEndEnd a <dd> tag.
divStart a <div> tag.
divEndEnd a <div> tag.
dlStart a <dl> tag.
dlEndEnd a <dl> tag.
docTypeWrite the XHTML Strict DOCTYPE.
docType5Write the HTML5 DOCTYPE.
dtStart a <dt> tag.
dtEndEnd a <dt> tag.
emStart a <em> tag.
emEndEnd a <em> tag.
escWrite obj.toStr to the stream as valid XML text.
favIconWrite a complete <link> tag for a favicon.
footerStart a <footer> tag.
footerEndEnd a <footer> tag.
formStart a <form> tag.
formEndEnd a <form> tag.
h1Start a <h1> tag.
h1EndEnd a <h1> tag.
h2Start a <h2> tag.
h2EndEnd a <h2> tag.
h3Start a <h3> tag.
h3EndEnd a <h3> tag.
h4Start a <h4> tag.
h4EndEnd a <h4> tag.
h5Start a <h5> tag.
h5EndEnd a <h5> tag.
h6Start a <h6> tag.
h6EndEnd a <h6> tag.
headStart a <head> tag.
headEndEnd a <head> tag.
headerStart a <header> tag.
headerEndEnd a <header> tag.
hiddenConvenience for input("type='hidden'" + attrs).
hrWrite out a complete <hr/> tag.
htmlStart a <html> tag.
htmlEndEnd a <html> tag.
iStart a <i> tag.
iEndEnd a <i> tag.
imgWrite a complete <img> tag.
includeCssWrite a complete <link> tag for an external CSS stylesheet.
includeJsWrite a complete <script> tag for an external JavaScript file.
initJsCustomize how the JavaScript runtime environment is initialized.
inputWrite a complete <input> tag.
labelStart a <label> tag.
labelEndEnd a <label> tag.
liStart a <li> tag.
liEndEnd a <li> tag.
mainStart a <main> tag.
mainEndEnd a <main> tag.
navStart a <nav> tag.
navEndEnd a <nav> tag.
nlConvenience for writeChar(\n).
olStart a <ol> tag.
olEndEnd a <ol> tag.
optionStart a <option> tag.
optionEndEnd a <option> tag.
pStart a <p> tag.
pEndEnd a <p> tag.
passwordConvenience for input("type='password'" + attrs).
preStart a <pre> tag.
preEndEnd a <pre> tag.
prologWrite out a prolog statement using the streams current charset encoding.
radioConvenience for input("type='radio'" + attrs)
rssWrite a complete <link> tag for a RSS feed resource.
scriptStart a <script> tag.
scriptEndEnd a <script> tag.
sectionStart a <section> tag.
sectionEndEnd a <section> tag.
selectStart a <select> tag.
selectEndEnd a <select> tag.
spanStart a <span> tag.
spanEndEnd a <span> tag.
styleStart a <style> tag.
styleEndEnd a <style> tag.
submitConvenience for input("type='submit'" + attrs).
tabConvenience for writeChars(Str.spaces(numSpaces)).
tableStart a <table> tag.
tableEndEnd a <table> tag.
tagWrite a start tag.
tagEndWrite an end tag.
tbodyStart a <tbody> tag.
tbodyEndEnd a <tbody> tag.
tdStart a <td> tag.
tdEndEnd a <td> tag.
textAreaStart a <textarea> tag.
textAreaEndEnd a <textarea> tag.
textFieldConvenience for input("type='text'" + attrs).
tfootStart a <tfoot> tag.
tfootEndEnd a <tfoot> tag.
thStart a <th> tag.
thEndEnd a <th> tag.
theadStart a <thead> tag.
theadEndEnd a <thead> tag.
titleWrite a complete <title> tag.
titleEndEnd a <title> tag.
trStart a <tr> tag.
trEndEnd a <tr> tag.
ulStart a <ul> tag.
ulEndEnd a <ul> tag.
wConvenience for writeChars(obj.toStr).

Slot Details ​


a ​

This a(Uri href, Str? attrs := null)

Start a <a> tag.


aEnd ​

This aEnd()

End a <a> tag.


article ​

This article(Str? attrs := null)

Start a <article> tag.


articleEnd ​

This articleEnd()

End a <article> tag.


aside ​

This aside(Str? attrs := null)

Start a <aside> tag.


asideEnd ​

This asideEnd()

End a <aside> tag.


atom ​

This atom(Uri href, Str? attrs := null)

Write a complete <link> tag for an Atom feed resource.


b ​

This b(Str? attrs := null)

Start a <b> tag.


bEnd ​

This bEnd()

End a <b> tag.


body ​

This body(Str? attrs := null)

Start a <body> tag.


bodyEnd ​

This bodyEnd()

End a <body> tag.


br ​

This br()

Write out a complete tag.


button ​

This button(Str? attrs := null)

Convenience for input("type='button'" + attrs).


checkbox ​

This checkbox(Str? attrs := null)

Convenience for input("type='checkbox'" + attrs)


code ​

This code(Str? attrs := null)

Start a <code> tag.


codeEnd ​

This codeEnd()

End a <code> tag.


dd ​

This dd(Str? attrs := null)

Start a <dd> tag.


ddEnd ​

This ddEnd()

End a <dd> tag.


div ​

This div(Str? attrs := null)

Start a <div> tag.


divEnd ​

This divEnd()

End a <div> tag.


dl ​

This dl(Str? attrs := null)

Start a <dl> tag.


dlEnd ​

This dlEnd()

End a <dl> tag.


docType ​

This docType()

Write the XHTML Strict DOCTYPE.


docType5 ​

This docType5()

Write the HTML5 DOCTYPE.


dt ​

This dt(Str? attrs := null)

Start a <dt> tag.


dtEnd ​

This dtEnd()

End a <dt> tag.


em ​

This em(Str? attrs := null)

Start a <em> tag.


emEnd ​

This emEnd()

End a <em> tag.


esc ​

This esc(Obj? obj)

Write obj.toStr to the stream as valid XML text. The special control characters amp, lt, apos and quot are always escaped. The gt char is escaped only if it is the first char or if preceeded by the ] char. Also see Str.toXml. If obj is null, then "null" is written.


favIcon ​

This favIcon(Uri href, Str? attrs := null)

Write a complete <link> tag for a favicon. You must specifiy the MIME type for your icon in the attrs argument:

out.favIcon(`/fav.png`, "type='image/png'")

This footer(Str? attrs := null)

Start a <footer> tag.


footerEnd ​

This footerEnd()

End a <footer> tag.


form ​

This form(Str? attrs := null)

Start a <form> tag.


formEnd ​

This formEnd()

End a <form> tag.


h1 ​

This h1(Str? attrs := null)

Start a <h1> tag.


h1End ​

This h1End()

End a <h1> tag.


h2 ​

This h2(Str? attrs := null)

Start a <h2> tag.


h2End ​

This h2End()

End a <h2> tag.


h3 ​

This h3(Str? attrs := null)

Start a <h3> tag.


h3End ​

This h3End()

End a <h3> tag.


h4 ​

This h4(Str? attrs := null)

Start a <h4> tag.


h4End ​

This h4End()

End a <h4> tag.


h5 ​

This h5(Str? attrs := null)

Start a <h5> tag.


h5End ​

This h5End()

End a <h5> tag.


h6 ​

This h6(Str? attrs := null)

Start a <h6> tag.


h6End ​

This h6End()

End a <h6> tag.


This head()

Start a <head> tag.


headEnd ​

This headEnd()

End a <head> tag.


This header(Str? attrs := null)

Start a <header> tag.


headerEnd ​

This headerEnd()

End a <header> tag.


hidden ​

This hidden(Str? attrs := null)

Convenience for input("type='hidden'" + attrs).


hr ​

This hr(Str? attrs := null)

Write out a complete <hr/> tag.


html ​

This html()

Start a <html> tag.


htmlEnd ​

This htmlEnd()

End a <html> tag.


i ​

This i(Str? attrs := null)

Start a <i> tag.


iEnd ​

This iEnd()

End a <i> tag.


img ​

This img(Uri src, Str? attrs := null)

Write a complete <img> tag.


includeCss ​

This includeCss(Uri href)

Write a complete <link> tag for an external CSS stylesheet. If this URI has already been included in this WebOutStream instance, then this method does nothing.


includeJs ​

This includeJs(Uri? href := null)

Write a complete <script> tag for an external JavaScript file. If this URI has already been included in this WebOutStream instance, then this method does nothing.


initJs ​

This initJs(Str:Str env)

Customize how the JavaScript runtime environment is initialized. This method must be called inside the <head> tag, and also before sys.js is loaded in order to take effect.

Note this method is not necessary if no customization is needed. The JS runtime will automatically initialize using default values.

The following variables are supported:

  • timezone: set the default TimeZone for JsVM

  • locale: set the default Locale for the JsVM. Note you must manually provide the locale config.props files. See FilePack.toLocaleJsFile.

  • main: an optional method to invoke after the page has been loaded. The main argument can be either a type or method. If no method is specified, main is used. If the method is not static, a new instance of type is created:

    "foo::Instance"     =>  Instance().main()
    "foo::Instance.bar" =>  Instance().bar()
    "foo::Static"       =>  Static.main()
    "foo::Static.bar"   =>  Static.bar()

input ​

This input(Str? attrs := null)

Write a complete <input> tag.


label ​

This label(Str? attrs := null)

Start a <label> tag.


labelEnd ​

This labelEnd()

End a <label> tag.


li ​

This li(Str? attrs := null)

Start a <li> tag.


liEnd ​

This liEnd()

End a <li> tag.


main ​

This main(Str? attrs := null)

Start a <main> tag.


mainEnd ​

This mainEnd()

End a <main> tag.


make ​

new make(OutStream out)

Construct a WebOutStream that wraps the given OutStream.


This nav(Str? attrs := null)

Start a <nav> tag.


This navEnd()

End a <nav> tag.


nl ​

This nl()

Convenience for writeChar(\n).


ol ​

This ol(Str? attrs := null)

Start a <ol> tag.


olEnd ​

This olEnd()

End a <ol> tag.


option ​

This option(Str? attrs := null)

Start a <option> tag.


optionEnd ​

This optionEnd()

End a <option> tag.


p ​

This p(Str? attrs := null)

Start a <p> tag.


pEnd ​

This pEnd()

End a <p> tag.


password ​

This password(Str? attrs := null)

Convenience for input("type='password'" + attrs).


pre ​

This pre(Str? attrs := null)

Start a <pre> tag.


preEnd ​

This preEnd()

End a <pre> tag.


prolog ​

This prolog()

Write out a prolog statement using the streams current charset encoding.


radio ​

This radio(Str? attrs := null)

Convenience for input("type='radio'" + attrs)


rss ​

This rss(Uri href, Str? attrs := null)

Write a complete <link> tag for a RSS feed resource.


script ​

This script(Str? attrs := "type='text/javascript'")

Start a <script> tag.


scriptEnd ​

This scriptEnd()

End a <script> tag.


section ​

This section(Str? attrs := null)

Start a <section> tag.


sectionEnd ​

This sectionEnd()

End a <section> tag.


select ​

This select(Str? attrs := null)

Start a <select> tag.


selectEnd ​

This selectEnd()

End a <select> tag.


span ​

This span(Str? attrs := null)

Start a <span> tag.


spanEnd ​

This spanEnd()

End a <span> tag.


style ​

This style(Str? attrs := "type='text/css'")

Start a <style> tag.


styleEnd ​

This styleEnd()

End a <style> tag.


submit ​

This submit(Str? attrs := null)

Convenience for input("type='submit'" + attrs).


tab ​

This tab(Int numSpaces := 2)

Convenience for writeChars(Str.spaces(numSpaces)).


table ​

This table(Str? attrs := null)

Start a <table> tag.


tableEnd ​

This tableEnd()

End a <table> tag.


tag ​

This tag(Str elemName, Str? attrs := null, Bool empty := false)

Write a start tag. Use attrs to fully specify the attributes manually. Use empty to optionally close this element without using an end tag.


tagEnd ​

This tagEnd(Str elemName)

Write an end tag.


tbody ​

This tbody(Str? attrs := null)

Start a <tbody> tag.


tbodyEnd ​

This tbodyEnd()

End a <tbody> tag.


td ​

This td(Str? attrs := null)

Start a <td> tag.


tdEnd ​

This tdEnd()

End a <td> tag.


textArea ​

This textArea(Str? attrs := null)

Start a <textarea> tag.


textAreaEnd ​

This textAreaEnd()

End a <textarea> tag.


textField ​

This textField(Str? attrs := null)

Convenience for input("type='text'" + attrs).


tfoot ​

This tfoot(Str? attrs := null)

Start a <tfoot> tag.


tfootEnd ​

This tfootEnd()

End a <tfoot> tag.


th ​

This th(Str? attrs := null)

Start a <th> tag.


thEnd ​

This thEnd()

End a <th> tag.


thead ​

This thead(Str? attrs := null)

Start a <thead> tag.


theadEnd ​

This theadEnd()

End a <thead> tag.


title ​

This title(Str? attrs := null)

Write a complete <title> tag.


titleEnd ​

This titleEnd()

End a <title> tag.


tr ​

This tr(Str? attrs := null)

Start a <tr> tag.


trEnd ​

This trEnd()

End a <tr> tag.


ul ​

This ul(Str? attrs := null)

Start a <ul> tag.


ulEnd ​

This ulEnd()

End a <ul> tag.


w ​

This w(Obj? obj)

Convenience for writeChars(obj.toStr).


WebReq ​

abstract class WebReq : Obj

WebReq encapsulates a web request.

See pod doc.

Fields

modGet the WebMod which is currently responsible for processing this request.
modBaseBase URI of the current WebMod.

Methods

absUriThe absolute request URI including the full authority and the query string.
cookiesMap of cookie values keyed by cookie name.
formGet the key/value pairs of the form data.
headersMap of HTTP request headers.
inGet the stream to read request body.
isGetReturn if the method is GET
isPostReturn if the method is POST
localesGet the accepted locales for this request based on the "Accept-Language" HTTP header.
methodThe HTTP request method in uppercase.
modRelWebMod relative part of the URI - see modBase.
parseMultiPartFormGiven a web request
remoteAddrGet the IP host address of the client socket making this request.
remotePortGet the IP port of the client socket making this request.
sessionGet the session associated with this browser "connection".
socketOptionsAccess to socket options for this request.
stashStash allows you to stash objects on the WebReq object in order to pass data b/w Weblets while processing this request.
uriThe request URI including the query string relative to this authority.
versionThe HTTP version of the request.

Slot Details ​


absUri ​

virtual Uri absUri()

The absolute request URI including the full authority and the query string. Also see uri, modBase, and modRel. This method is equivalent to:

"http://" + headers["Host"] + uri

Examples:

http://www.foo.com/a/b/c
http://www.foo.com/a?q=bar

cookies ​

virtual Str:Str cookies()

Map of cookie values keyed by cookie name. The cookies map is readonly and case insensitive.


form ​

virtual [Str:Str]? form()

Get the key/value pairs of the form data. If the request content type is "application/x-www-form-urlencoded", then the first time this method is called the request content is read and parsed using Uri.decodeQuery. If the content type is not "application/x-www-form-urlencoded" this method returns null.


headers ​

abstract Str:Str headers()

Map of HTTP request headers. The headers map is readonly and case insensitive (see Map.caseInsensitive).

Examples:

req.headers["Accept-Language"]

in ​

abstract InStream in()

Get the stream to read request body. See WebUtil.makeContentInStream to check under which conditions request content is available. If request content is not available, then throw an exception.

If the client specified the "Expect: 100-continue" header, then the first access of the request input stream will automatically send the client a 100 Continue response.


isGet ​

abstract Bool isGet()

Return if the method is GET


isPost ​

abstract Bool isPost()

Return if the method is POST


locales ​

virtual Locale[] locales()

Get the accepted locales for this request based on the "Accept-Language" HTTP header. List is sorted by preference, where locales.first is best, and locales.last is worst. This list is guarenteed to contain Locale("en").


method ​

abstract Str method()

The HTTP request method in uppercase. Example: GET, POST, PUT.


mod ​

abstract WebMod mod

Get the WebMod which is currently responsible for processing this request.


modBase ​

Uri modBase := `/`

Base URI of the current WebMod. This Uri always ends in a slash. This is the URI used to route to the WebMod itself. The remainder of uri is stored in modRel so that the following always holds true (with exception of a trailing slash):

modBase + modRel == uri

For example if the current WebMod is mounted as /mod then:

uri          modBase   modRel
----------   -------   -------
`/mod`       `/mod/`   ``
`/mod/`      `/mod/`   ``
`/mod?q`     `/mod/`   `?q`
`/mod/a`     `/mod/`   `a`
`/mod/a/b`   `/mod/`   `a/b`

modRel ​

Uri modRel()

WebMod relative part of the URI - see modBase.


parseMultiPartForm ​

Void parseMultiPartForm(|Str,InStream,Str:Str| cb)

Given a web request:

  1. check that the content-type is form-data
  2. get the boundary string
  3. invoke callback for each part (see WebUtil.parseMultiPart)

For each part in the stream call the given callback function with the part's form name, headers, and an input stream used to read the part's body.


remoteAddr ​

abstract IpAddr remoteAddr()

Get the IP host address of the client socket making this request.


remotePort ​

abstract Int remotePort()

Get the IP port of the client socket making this request.


session ​

abstract WebSession session()

Get the session associated with this browser "connection". The session must be accessed the first time before the response is committed.


socketOptions ​

abstract SocketOptions socketOptions()

Access to socket options for this request.


stash ​

virtual Str:Obj? stash()

Stash allows you to stash objects on the WebReq object in order to pass data b/w Weblets while processing this request.


uri ​

abstract Uri uri()

The request URI including the query string relative to this authority. Also see absUri, modBase, and modRel.

Examples:

/a/b/c
/a?q=bar

version ​

abstract Version version()

The HTTP version of the request.


WebRes ​

abstract class WebRes : Obj

WebRes encapsulates a response to a web request.

See pod doc

Fields

statusCodeGet or set the HTTP status code for this response.
statusMsgMap of HTTP status codes to status messages.
statusPhraseReason phrase to include in HTTP response line.

Methods

cookiesGet the list of cookies to set via header fields.
doneDone is called to indicate that that response is complete to terminate pipeline processing.
headersMap of HTTP response headers.
isCommittedReturn true if this response has been commmited.
isDoneReturn if this response is complete - see done.
outReturn the WebOutStream for this response.
redirectSend a redirect response to the client using the specified status code and url.
removeCookieRemove a cookie for this response.
sendErrSend an error response to client using the specified status and HTML formatted message.

Slot Details ​


cookies ​

abstract Cookie[] cookies()

Get the list of cookies to set via header fields. Add a a Cookie to this list to set a cookie. Throw an err if response is already committed.

Example:

res.cookies.add(Cookie("foo", "123"))
res.cookies.add(Cookie("persistent", "some val") { maxAge = 3day })

done ​

abstract Void done()

Done is called to indicate that that response is complete to terminate pipeline processing.


headers ​

abstract Str:Str headers()

Map of HTTP response headers. You must set all headers before you access out() for the first time, which commits the response. Throw an err if response is already committed.


isCommitted ​

abstract Bool isCommitted()

Return true if this response has been commmited. A committed response has written its response headers, and can no longer modify its status code or headers. A response is committed the first time that out is called.


isDone ​

abstract Bool isDone()

Return if this response is complete - see done.


out ​

abstract WebOutStream out()

Return the WebOutStream for this response. The first time this method is accessed the response is committed: all headers currently set will be written to the stream, and can no longer be modified. If the "Content-Length" header defines a fixed number of bytes, then attemps to write too many bytes will throw an IOErr. If "Content-Length" is not defined, then a chunked transfer encoding is automatically used.


redirect ​

abstract Void redirect(Uri uri, Int statusCode := 303)

Send a redirect response to the client using the specified status code and url. If this response has already been committed this method throws an Err. This method implicitly calls done.


removeCookie ​

Void removeCookie(Str name)

Remove a cookie for this response. This method is a convenience for:

res.cookies.add(Cookie(name, "") { maxAge=0day }

sendErr ​

abstract Void sendErr(Int statusCode, Str? msg := null)

Send an error response to client using the specified status and HTML formatted message. If this response has already been committed this method throws an Err. This method implicitly calls done.


statusCode ​

abstract Int statusCode

Get or set the HTTP status code for this response. Status code defaults to 200. Throw an err if the response has already been committed.


statusMsg ​

const static Int:Str statusMsg := ...

Map of HTTP status codes to status messages.


statusPhrase ​

abstract Str? statusPhrase

Reason phrase to include in HTTP response line. If null, then a status phrase is used based on the statusCode.


WebSession ​

abstract class WebSession : Obj

WebSession provides a name/value map associated with a specific browser "connection" to the web server. Any values stored in a WebSession must be both immutable and serializable. Get the current WebSession via WebReq.session.

See pod doc.

Methods

deleteDelete this web session which clears both the user agent cookie and the server side session instance.
eachIterate the key/value pairs
getGet session value or return def if not defined.
idGet the unique id used to identify this session.
mapApplication name/value pairs which are persisted between HTTP requests.
removeRemove a session key
setSet a session value which must be immutable and serializable.
toStrReturn id.

Slot Details ​


delete ​

abstract Void delete()

Delete this web session which clears both the user agent cookie and the server side session instance. This method must be called before the WebRes is committed otherwise the server side instance is cleared, but the user agent cookie will remain uncleared.


each ​

abstract Void each(|Obj?,Str| f)

Iterate the key/value pairs


get ​

@Operator abstract Obj? get(Str name, Obj? def := null)

Get session value or return def if not defined.


id ​

abstract Str id()

Get the unique id used to identify this session.


map ​

@Deprecated { msg="Use get, set, remove, each" } abstract Str:Obj? map()

Application name/value pairs which are persisted between HTTP requests. The values stored in this map must be serializable.


remove ​

abstract Void remove(Str name)

Remove a session key


set ​

@Operator abstract Void set(Str name, Obj? val)

Set a session value which must be immutable and serializable.


toStr ​

virtual override Str toStr()

Return id.


WebSocket ​

class WebSocket : Obj

WebSocket is used for both client and server web socket messaging. Current implementation only supports basic non-fragmented text or binary messages.

Methods

closeClose the web socket
isClosedReturn true if this socket has been closed
openClientOpen a client connection.
openServerUpgrade a server request to a WebSocket.
receiveReceive a message which is returned as either a Str or Buf.
sendSend a message which must be either a Str of Buf.
socketOptionsAccess to socket options for this request.

Slot Details ​


close ​

Bool close()

Close the web socket


isClosed ​

Bool isClosed()

Return true if this socket has been closed


openClient ​

static WebSocket openClient(Uri uri, [Str:Str]? headers := null)

Open a client connection. The URI must have a "ws" or "wss" scheme. The headers parameter defines additional HTTP headers to include in the connection request.


openServer ​

static WebSocket openServer(WebReq req, WebRes res)

Upgrade a server request to a WebSocket. Raise IOErr is there is any problems during the handshake in which case the calling WebMod should return a 400 response.

Callers should set the Sec-WebSocket-Protocol response header before calling this method. However, if not set then this call will set it to the request header value for Sec-WebSocket-Protocol (if available).

Note: once this method completes, the socket is now owned by the WebSocket instance and not the web server (wisp); it must be explicitly closed to prevent a file handle leak.


receive ​

Obj? receive()

Receive a message which is returned as either a Str or Buf. Raise IOErr if socket has error or is closed.


send ​

Void send(Obj msg)

Send a message which must be either a Str of Buf. Bufs are sent using their full contents irrelevant of their current position.


socketOptions ​

@Deprecated { msg=... } SocketOptions socketOptions()

Access to socket options for this request.


WebUtil ​

@Js class WebUtil : Obj

WebUtil encapsulates several useful utility web methods. Also see MimeType and its utility methods.

Methods

fromQuotedStrDecode a HTTP quoted string according to RFC 2616 Section 2.2.
headersToCharsetGiven a set of HTTP headers map Content-Type to its charset or default to UTF-8.
isTokenReturn if the specified string is a valid HTTP token production which is any ASCII character which is not a control char or a separator.
isTokenCharReturn if given char unicode point is allowable within the HTTP token production.
jsMainGenerate the method invocation code used to boostrap into JavaScript from a webpage.
makeChunkedInStreamWrap the given input stream to read bytes using a HTTP chunked transfer encoding.
makeChunkedOutStreamWrap the given output stream to write bytes using a HTTP chunked transfer encoding.
makeContentInStreamGiven a set of headers, wrap the specified input stream to read the content body
makeContentOutStreamGiven a set of headers, wrap the specified output stream to write the content body
makeFixedInStreamWrap the given input stream to read a fixed number of bytes.
makeFixedOutStreamWrap the given output stream to write a fixed number of bytes.
parseHeadersParse a series of HTTP headers according to RFC 2616 section 4.2.
parseListParse a list of comma separated tokens.
parseMultiPartParse a multipart/form-data input stream.
parseQValsGiven an HTTP header that uses q values, return a map of name/q-value pairs.
toQuotedStrReturn the specified string as a HTTP quoted string according to RFC 2616 Section 2.2.

Slot Details ​


fromQuotedStr ​

static Str fromQuotedStr(Str s)

Decode a HTTP quoted string according to RFC 2616 Section 2.2. The given string must be wrapped in quotes. See toQuotedStr.


headersToCharset ​

static Charset headersToCharset(Str:Str headers)

Given a set of HTTP headers map Content-Type to its charset or default to UTF-8.


isToken ​

static Bool isToken(Str s)

Return if the specified string is a valid HTTP token production which is any ASCII character which is not a control char or a separator. The separators characters are:

"(" | ")" | "<" | ">" | "@" |
"," | ";" | ":" | "\" | <"> |
"/" | "[" | "]" | "?" | "=" |
"{" | "}" | SP | HT

isTokenChar ​

static Bool isTokenChar(Int c)

Return if given char unicode point is allowable within the HTTP token production. See isToken.


jsMain ​

@Deprecated { msg="use WebOutStream.initJs" } static Void jsMain(OutStream out, Str main, [Str:Str]? env := null)

Generate the method invocation code used to boostrap into JavaScript from a webpage. This must be called inside the <head> tag for the page. The main method will be invoked using the onLoad DOM event.

The main argument can be either a type or method. If no method is specified, main is used. If the method is not static, a new instance of type is created:

"foo::Instance"     =>  Instance().main()
"foo::Instance.bar" =>  Instance().bar()
"foo::Static"       =>  Static.main()
"foo::Static.bar"   =>  Static.bar()

If env is specified, then vars will be added to and available from Env.vars on client-side.


makeChunkedInStream ​

static InStream makeChunkedInStream(InStream in)

Wrap the given input stream to read bytes using a HTTP chunked transfer encoding. The wrapped streams provides a contiguous stream of bytes until the last chunk is read. Closing the wrapper stream does not close the underlying stream.


makeChunkedOutStream ​

static OutStream makeChunkedOutStream(OutStream out)

Wrap the given output stream to write bytes using a HTTP chunked transfer encoding. Closing the wrapper stream terminates the chunking, but does not close the underlying stream.


makeContentInStream ​

static InStream makeContentInStream(Str:Str headers, InStream in)

Given a set of headers, wrap the specified input stream to read the content body:

  1. If Content-Encoding is gzip then wrap via Zip.gzipInStream
  2. If Content-Length then makeFixedInStream
  3. If Transfer-Encoding is chunked then makeChunkedInStream
  4. If Content-Type assume non-pipelined connection and return in directly

If a stream is returned, then it is automatically configured with the correct content encoding based on the Content-Type.


makeContentOutStream ​

static OutStream? makeContentOutStream(Str:Str headers, OutStream out)

Given a set of headers, wrap the specified output stream to write the content body:

  1. If Content-Length then makeFixedOutStream
  2. If Content-Type then set Transfer-Encoding header to chunked and return makeChunkedOutStream
  3. Assume no content and return null

If a stream is returned, then it is automatically configured with the correct content encoding based on the Content-Type.


makeFixedInStream ​

static InStream makeFixedInStream(InStream in, Int fixed)

Wrap the given input stream to read a fixed number of bytes. Once fixed bytes have been read from the underlying input stream, the wrapped stream will return end-of-stream. Closing the wrapper stream does not close the underlying stream.


makeFixedOutStream ​

static OutStream makeFixedOutStream(OutStream out, Int fixed)

Wrap the given output stream to write a fixed number of bytes. Once fixed bytes have been written, attempting to further bytes will throw IOErr. Closing the wrapper stream does not close the underlying stream.


parseHeaders ​

static Str:Str parseHeaders(InStream in)

Parse a series of HTTP headers according to RFC 2616 section 4.2. The final CRLF which terminates headers is consumed with the stream positioned immediately following. The headers are returned as a case insensitive map. Throw ParseErr if headers are malformed.


parseList ​

static Str[] parseList(Str s)

Parse a list of comma separated tokens. Any leading or trailing whitespace is trimmed from the list of tokens.


parseMultiPart ​

static Void parseMultiPart(InStream in, Str boundary, |Str:Str,InStream| cb)

Parse a multipart/form-data input stream. For each part in the stream call the given callback function with the part's headers and an input stream used to read the part's body. Each callback must completely drain the input stream to prepare for the next part. Also see WebReq.parseMultiPartForm.


parseQVals ​

static Str:Float parseQVals(Str s)

Given an HTTP header that uses q values, return a map of name/q-value pairs. This map has a def value of 0.

Example:

compress,gzip              =>  ["compress":1f, "gzip":1f]
compress;q=0.5,gzip;q=0.0  =>  ["compress":0.5f, "gzip":0.0f]

toQuotedStr ​

static Str toQuotedStr(Str s)

Return the specified string as a HTTP quoted string according to RFC 2616 Section 2.2. The result is wrapped in quotes. Throw ArgErr if any character is outside of the ASCII range of 0x20 to 0x7e. The quote char itself is backslash escaped. See fromQuotedStr.


Weblet ​

mixin Weblet

Weblet services a web request.

See pod doc.

Methods

onDeleteConvenience method to respond to a DELETE request.
onGetConvenience method to respond to a GET request.
onHeadConvenience method to respond to a HEAD request.
onOptionsConvenience method to respond to a OPTIONS request.
onPostConvenience method to respond to a POST request.
onPutConvenience method to respond to a PUT request.
onServiceService a web request.
onTraceConvenience method to respond to a TRACE request.
reqThe WebReq instance for this current web request.
resThe WebRes instance for this current web request.

Slot Details ​


onDelete ​

virtual Void onDelete()

Convenience method to respond to a DELETE request. Default implementation returns a 501 Not implemented error.


onGet ​

virtual Void onGet()

Convenience method to respond to a GET request. Default implementation returns a 501 Not implemented error.


onHead ​

virtual Void onHead()

Convenience method to respond to a HEAD request. Default implementation returns a 501 Not implemented error.


onOptions ​

virtual Void onOptions()

Convenience method to respond to a OPTIONS request. Default implementation returns a 501 Not implemented error.


onPost ​

virtual Void onPost()

Convenience method to respond to a POST request. Default implementation returns a 501 Not implemented error.


onPut ​

virtual Void onPut()

Convenience method to respond to a PUT request. Default implementation returns a 501 Not implemented error.


onService ​

virtual Void onService()

Service a web request. The default implementation routes to onGet, onPost, etc based on the request's method.


onTrace ​

virtual Void onTrace()

Convenience method to respond to a TRACE request. Default implementation returns a 501 Not implemented error.


req ​

virtual WebReq req()

The WebReq instance for this current web request. Raise an exception if the current actor thread is not serving a web request.


res ​

virtual WebRes res()

The WebRes instance for this current web request. Raise an exception if the current actor thread is not serving a web request.