外观
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:
- configure request fields such as
reqUri,reqMethod, andreqHeaders - send request headers via
writeReq - optionally write request body via
reqOut - read response status and headers via
readRes - process response fields such as
resCodeandresHeaders - 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"
reqandres: the current actor'sWebReqandWebResare available with these methods - so there no need to pass the request and response aroundonService: theonServicemethod can be overridden directly to handle the request, or the default implementation will route to thedoGet,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 aUriwhich allows you access the parsed path and query segments.mod: web module currently responsible for requestmodBase: URI used to route to current modulemodRel: module relative URI used for module internal processingheaders: a case insensitiveStr:Strmap of the request HTTP headersin: access to the raw input stream of the requestform: access to the parsed form datacookies: aStr:Strmap of cookiessession: aStr:Objmap used to stash stuff for the browser "connection" between HTTP requestsstash: aStr:Objmap 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, andcookiesare 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, orsendErrwill raise an exception - Done: at this point the response is complete - for example once the
redirectorsendErrmethod is called, the response is done
Common methods you will use include:
statusCode: sets the HTTP status code - must be set before commitheaders: aStr:Strmap of HTTP headers - must be set before commitcookies: used to set the cookie header - must be set before commitout: the output stream for writing the content - first call commits the responseisCommitted: check commit stateisDone: check done statesendErr: used to send an error status coderedirect: 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
| fromStr | Parse a HTTP cookie header name/value pair. |
| make | Construct with name and value. |
Fields
| domain | Specifies the domain for which the cookie is valid. |
| httpOnly | If true, then the cookie is not available to JavaScript. |
| maxAge | Defines the lifetime of the cookie, after the the max-age elapses the client should discard the cookie. |
| name | Name of the cookie. |
| path | Specifies the subset of URLs to which the cookie applies. |
| sameSite | If this value is non-null, then we add the SameSite attribute to the cookie. |
| secure | If true, then the client only sends this cookie using a secure protocol such as HTTPS. |
| val | Value string of the cookie. |
Methods
| toStr | Return 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", "")).readAllStrmaxAge
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
laxstrictBy default we set the attribute tostrict
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
| makeFiles | Construct a bundle for the given list of text files |
Methods
| onGet | Service an HTTP GET request for this bundle file |
| pack | Pack multiple text files together and write to the given output stream. |
| toAppCssFiles | Given a set of pods return a list of CSS files that form a complete Fantom application |
| toAppJsFiles | Given a set of pods return a list of JavaScript files that form a complete Fantom application |
| toEtcJsFiles | Return the required sys etc files |
| toIndexPropsJsFile | Compile the indexed props database into a JavaScript file "index-props.js" |
| toLocaleJsFile | Compile the locale props into a JavaScript file "{locale}.js" |
| toMimeJsFile | Compile the mime type database into a Javascript file "mime.js" |
| toPodCssFiles | Map a set of pods to "/res/css/{name}.css" CSS files. |
| toPodJsFile | Get the standard pod JavaScript file or null if no JS code. |
| toPodJsFiles | Map a set of pods to "/{name}.js" JavaScript files. |
| toPodJsMapFile | Compile a list of pod JavaScript files into a single unified source map file. |
| toTimezonesJsFile | Compile the timezone database into a JavaScript file "tz.js" |
| toUnitsJsFile | Compile 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
toEtcJsFilesimmediately 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
| make | Constructor with file to service. |
Fields
| extraResHeaders | Extra response headers to add for all 3xx and 2xx responses |
| file | The file being serviced by this FileWeblet. |
Methods
| checkNotModified | Check if the request passed headers indicating it has cached version of the file. |
| checkUnderDir | Checks if the file being served is under the given directory. |
| etag | Compute the ETag for the file being serviced which uniquely identifies the file version. |
| modified | Get the modified time of the file floored to 1 second which is the most precise that HTTP can deal with. |
| onGet | Handle 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).onServiceetag
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:
- configure request fields such as
reqUri,reqMethod, andreqHeaders - send request headers via
writeReq - optionally write request body via
reqOut - read response status and headers via
readRes - process response fields such as
resCodeandresHeaders - 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.
Constructors
| make | Construct with optional request URI. |
Fields
| cookies | Cookies to pass for "Cookie" request header. |
| followRedirects | 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. |
| proxy | If non-null, then all requests are routed through this proxy address (host and port). |
| reqHeaders | The HTTP headers to use for the next request. |
| reqMethod | The HTTP method for the request. |
| reqUri | The absolute URI of request. |
| reqVersion | HTTP version to use for request must be 1.0 or 1.1. |
| resCode | HTTP status code returned by response. |
| resHeaders | HTTP headers returned by response. |
| resPhrase | HTTP status reason phrase returned by response. |
| resVersion | HTTP version returned by response. |
| socketConfig | The SocketConfig to use for creating sockets |
Methods
| authBasic | Authenticate request using HTTP Basic with given username and password. |
| close | Close the HTTP request and the underlying socket. |
| getBuf | Make a GET request and return the response content as an in-memory byte buffer. |
| getIn | Make a GET request and return the input stream to the response or throw IOErr if response is not 200. |
| getStr | Make a GET request and return the response content as an in-memory string. |
| isConnected | Return if this web client is currently connected to the remote host. |
| postBuf | Convenience for writeBuf("POST", content).readRes |
| postFile | Convenience for writeFile("POST", file).readRes |
| postForm | Convenience for writeForm("POST", form).readRes |
| postStr | Convenience for writeStr("POST", content).readRes |
| readRes | Read the response status line and response headers. |
| reqOut | Get the output stream used to write the request body. |
| resBuf | Return the entire response back as an in-memory byte buffer. |
| resHeader | Get a response header. |
| resIn | Input stream to read response content. |
| resStr | Return the entire response back as an in-memory string. |
| socketOptions | |
| writeBuf | Write a binary buffer using the given HTTP method to the URI. |
| writeFile | Write a file using the given HTTP method to the URI. |
| writeForm | Make a request with the given HTTP method to the URI with the given form data. |
| writeReq | Write the request line and request headers. |
| writeStr | Make 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
| onStart | Initialization callback when web server is started. |
| onStop | Cleanup 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
| make | Construct a WebOutStream that wraps the given OutStream. |
Methods
| a | Start a <a> tag. |
| aEnd | End a <a> tag. |
| article | Start a <article> tag. |
| articleEnd | End a <article> tag. |
| aside | Start a <aside> tag. |
| asideEnd | End a <aside> tag. |
| atom | Write a complete <link> tag for an Atom feed resource. |
| b | Start a <b> tag. |
| bEnd | End a <b> tag. |
| body | Start a <body> tag. |
| bodyEnd | End a <body> tag. |
| br | Write out a complete tag. |
| button | Convenience for input("type='button'" + attrs). |
| checkbox | Convenience for input("type='checkbox'" + attrs) |
| code | Start a <code> tag. |
| codeEnd | End a <code> tag. |
| dd | Start a <dd> tag. |
| ddEnd | End a <dd> tag. |
| div | Start a <div> tag. |
| divEnd | End a <div> tag. |
| dl | Start a <dl> tag. |
| dlEnd | End a <dl> tag. |
| docType | Write the XHTML Strict DOCTYPE. |
| docType5 | Write the HTML5 DOCTYPE. |
| dt | Start a <dt> tag. |
| dtEnd | End a <dt> tag. |
| em | Start a <em> tag. |
| emEnd | End a <em> tag. |
| esc | Write obj.toStr to the stream as valid XML text. |
| favIcon | Write a complete <link> tag for a favicon. |
| footer | Start a <footer> tag. |
| footerEnd | End a <footer> tag. |
| form | Start a <form> tag. |
| formEnd | End a <form> tag. |
| h1 | Start a <h1> tag. |
| h1End | End a <h1> tag. |
| h2 | Start a <h2> tag. |
| h2End | End a <h2> tag. |
| h3 | Start a <h3> tag. |
| h3End | End a <h3> tag. |
| h4 | Start a <h4> tag. |
| h4End | End a <h4> tag. |
| h5 | Start a <h5> tag. |
| h5End | End a <h5> tag. |
| h6 | Start a <h6> tag. |
| h6End | End a <h6> tag. |
| head | Start a <head> tag. |
| headEnd | End a <head> tag. |
| header | Start a <header> tag. |
| headerEnd | End a <header> tag. |
| hidden | Convenience for input("type='hidden'" + attrs). |
| hr | Write out a complete <hr/> tag. |
| html | Start a <html> tag. |
| htmlEnd | End a <html> tag. |
| i | Start a <i> tag. |
| iEnd | End a <i> tag. |
| img | Write a complete <img> tag. |
| includeCss | Write a complete <link> tag for an external CSS stylesheet. |
| includeJs | Write a complete <script> tag for an external JavaScript file. |
| initJs | Customize how the JavaScript runtime environment is initialized. |
| input | Write a complete <input> tag. |
| label | Start a <label> tag. |
| labelEnd | End a <label> tag. |
| li | Start a <li> tag. |
| liEnd | End a <li> tag. |
| main | Start a <main> tag. |
| mainEnd | End a <main> tag. |
| nav | Start a <nav> tag. |
| navEnd | End a <nav> tag. |
| nl | Convenience for writeChar(\n). |
| ol | Start a <ol> tag. |
| olEnd | End a <ol> tag. |
| option | Start a <option> tag. |
| optionEnd | End a <option> tag. |
| p | Start a <p> tag. |
| pEnd | End a <p> tag. |
| password | Convenience for input("type='password'" + attrs). |
| pre | Start a <pre> tag. |
| preEnd | End a <pre> tag. |
| prolog | Write out a prolog statement using the streams current charset encoding. |
| radio | Convenience for input("type='radio'" + attrs) |
| rss | Write a complete <link> tag for a RSS feed resource. |
| script | Start a <script> tag. |
| scriptEnd | End a <script> tag. |
| section | Start a <section> tag. |
| sectionEnd | End a <section> tag. |
| select | Start a <select> tag. |
| selectEnd | End a <select> tag. |
| span | Start a <span> tag. |
| spanEnd | End a <span> tag. |
| style | Start a <style> tag. |
| styleEnd | End a <style> tag. |
| submit | Convenience for input("type='submit'" + attrs). |
| tab | Convenience for writeChars(Str.spaces(numSpaces)). |
| table | Start a <table> tag. |
| tableEnd | End a <table> tag. |
| tag | Write a start tag. |
| tagEnd | Write an end tag. |
| tbody | Start a <tbody> tag. |
| tbodyEnd | End a <tbody> tag. |
| td | Start a <td> tag. |
| tdEnd | End a <td> tag. |
| textArea | Start a <textarea> tag. |
| textAreaEnd | End a <textarea> tag. |
| textField | Convenience for input("type='text'" + attrs). |
| tfoot | Start a <tfoot> tag. |
| tfootEnd | End a <tfoot> tag. |
| th | Start a <th> tag. |
| thEnd | End a <th> tag. |
| thead | Start a <thead> tag. |
| theadEnd | End a <thead> tag. |
| title | Write a complete <title> tag. |
| titleEnd | End a <title> tag. |
| tr | Start a <tr> tag. |
| trEnd | End a <tr> tag. |
| ul | Start a <ul> tag. |
| ulEnd | End a <ul> tag. |
| w | Convenience 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'")footer
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.
head
This head()
Start a <head> tag.
headEnd
This headEnd()
End a <head> tag.
header
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 JsVMlocale: set the default Locale for the JsVM. Note you must manually provide the locale config.props files. SeeFilePack.toLocaleJsFile.main: an optional method to invoke after the page has been loaded. Themainargument can be either a type or method. If no method is specified,mainis 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.
nav
This nav(Str? attrs := null)
Start a <nav> tag.
navEnd
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
| mod | Get the WebMod which is currently responsible for processing this request. |
| modBase | Base URI of the current WebMod. |
Methods
| absUri | The absolute request URI including the full authority and the query string. |
| cookies | Map of cookie values keyed by cookie name. |
| form | Get the key/value pairs of the form data. |
| headers | Map of HTTP request headers. |
| in | Get the stream to read request body. |
| isGet | Return if the method is GET |
| isPost | Return if the method is POST |
| locales | Get the accepted locales for this request based on the "Accept-Language" HTTP header. |
| method | The HTTP request method in uppercase. |
| modRel | WebMod relative part of the URI - see modBase. |
| parseMultiPartForm | Given a web request |
| remoteAddr | Get the IP host address of the client socket making this request. |
| remotePort | Get the IP port of the client socket making this request. |
| session | Get the session associated with this browser "connection". |
| socketOptions | Access to socket options for this request. |
| stash | Stash allows you to stash objects on the WebReq object in order to pass data b/w Weblets while processing this request. |
| uri | The request URI including the query string relative to this authority. |
| version | The 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"] + uriExamples:
http://www.foo.com/a/b/c
http://www.foo.com/a?q=barcookies
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 == uriFor 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:
- check that the content-type is form-data
- get the boundary string
- 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=barversion
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
| statusCode | Get or set the HTTP status code for this response. |
| statusMsg | Map of HTTP status codes to status messages. |
| statusPhrase | Reason phrase to include in HTTP response line. |
Methods
| cookies | Get the list of cookies to set via header fields. |
| done | Done is called to indicate that that response is complete to terminate pipeline processing. |
| headers | Map of HTTP response headers. |
| isCommitted | Return true if this response has been commmited. |
| isDone | Return if this response is complete - see done. |
| out | Return the WebOutStream for this response. |
| redirect | Send a redirect response to the client using the specified status code and url. |
| removeCookie | Remove a cookie for this response. |
| sendErr | Send 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
| delete | Delete this web session which clears both the user agent cookie and the server side session instance. |
| each | Iterate the key/value pairs |
| get | Get session value or return def if not defined. |
| id | Get the unique id used to identify this session. |
| map | Application name/value pairs which are persisted between HTTP requests. |
| remove | Remove a session key |
| set | Set a session value which must be immutable and serializable. |
| toStr | Return 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
| close | Close the web socket |
| isClosed | Return true if this socket has been closed |
| openClient | Open a client connection. |
| openServer | Upgrade a server request to a WebSocket. |
| receive | Receive a message which is returned as either a Str or Buf. |
| send | Send a message which must be either a Str of Buf. |
| socketOptions | Access 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
| fromQuotedStr | Decode a HTTP quoted string according to RFC 2616 Section 2.2. |
| headersToCharset | Given a set of HTTP headers map Content-Type to its charset or default to UTF-8. |
| isToken | 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. |
| isTokenChar | Return if given char unicode point is allowable within the HTTP token production. |
| jsMain | Generate the method invocation code used to boostrap into JavaScript from a webpage. |
| makeChunkedInStream | Wrap the given input stream to read bytes using a HTTP chunked transfer encoding. |
| makeChunkedOutStream | Wrap the given output stream to write bytes using a HTTP chunked transfer encoding. |
| makeContentInStream | Given a set of headers, wrap the specified input stream to read the content body |
| makeContentOutStream | Given a set of headers, wrap the specified output stream to write the content body |
| makeFixedInStream | Wrap the given input stream to read a fixed number of bytes. |
| makeFixedOutStream | Wrap the given output stream to write a fixed number of bytes. |
| parseHeaders | Parse a series of HTTP headers according to RFC 2616 section 4.2. |
| parseList | Parse a list of comma separated tokens. |
| parseMultiPart | Parse a multipart/form-data input stream. |
| parseQVals | Given an HTTP header that uses q values, return a map of name/q-value pairs. |
| toQuotedStr | Return 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 | HTisTokenChar
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:
- If Content-Encoding is
gzipthen wrap viaZip.gzipInStream - If Content-Length then
makeFixedInStream - If Transfer-Encoding is chunked then
makeChunkedInStream - If Content-Type assume non-pipelined connection and return
indirectly
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:
- If Content-Length then
makeFixedOutStream - If Content-Type then set Transfer-Encoding header to chunked and return
makeChunkedOutStream - 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
| onDelete | Convenience method to respond to a DELETE request. |
| onGet | Convenience method to respond to a GET request. |
| onHead | Convenience method to respond to a HEAD request. |
| onOptions | Convenience method to respond to a OPTIONS request. |
| onPost | Convenience method to respond to a POST request. |
| onPut | Convenience method to respond to a PUT request. |
| onService | Service a web request. |
| onTrace | Convenience method to respond to a TRACE request. |
| req | The WebReq instance for this current web request. |
| res | The 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.