YAWS_API(5)
β¨ NAME β¨
yaws_api β the api available to yaws web server programmers. And welcome to YAWS_API(5), bestie! This is where all the yaws_api magic lives. π
π¦ SYNOPSIS π¦
yaws_api:Function(...)
πΈ DESCRIPTION πΈ
Okay so this is the api available to yaws web server programmers. The Erlang module yaws_api contains a wide variety of functions that can be used inside yaws pages. β¨
Each chunk of yaws code is executed while the yaws page is being delivered from the server. Let's do a super simple example to show the vibe. Imagine this HTML:
<html>
<body>
<h1> Header 1</h1>
<erl>
out(Arg) ->
{html, "<p> Insert this text into the document"}.
</erl>
</body>
</html>
The out(Arg) function is supplied one argument, an #arg{} structure. We have the following relevant record definitions:
-record(arg, {
clisock, % the socket leading to the peer client
client_ip_port, % {ClientIp, ClientPort} tuple
headers, % headers
req, % request (possibly rewritten)
orig_req, % original request
clidata, % The client data (as a binary in POST requests)
server_path, % The normalized server path
% (pre-querystring part of URI)
querydata, % For URIs of the form ...?querydata
% equiv of cgi QUERY_STRING
appmoddata, % (deprecated - use pathinfo instead) the remainder
% of the path leading up to the query
docroot, % Physical base location of data for this request
docroot_mount, % virtual directory e.g /myapp/ that the docroot
% refers to.
fullpath, % full deep path to yaws file
cont, % Continuation for chunked multipart uploads
state, % State for use by users of the out/1 callback
pid, % pid of the yaws worker process
opaque, % useful to pass static data
appmod_prepath, % (deprecated - use prepath instead) path in front
% of: <appmod><appmoddata>
prepath, % Path prior to 'dynamic' segment of URI.
% ie http://some.host/<prepath>/<script-point>/d/e
% where <script-point> is an appmod mount point,
% or .yaws,.php,.cgi,.fcgi etc script file.
pathinfo, % Set to '/d/e' when calling c.yaws for the request
% http://some.host/a/b/c.yaws/d/e
% equiv of cgi PATH_INFO
appmod_name % name of the appmod handling a request,
% or undefined if not applicable
}).
The headers argument is also a record:
-record(headers, {
connection,
accept,
host,
if_modified_since,
if_match,
if_none_match,
if_range,
if_unmodified_since,
range,
referer,
user_agent,
accept_ranges,
cookie = [],
keep_alive,
location,
content_length,
content_type,
content_encoding,
authorization,
transfer_encoding,
x_forwarded_for,
other = [] % misc other headers
}).
The out/1 function can use the Arg to generate any content it likes. We have the following functions to aid that generation. π«Ά
π API π
Now the good stuff! Each function, slay.
ssi(DocRoot, ListOfFiles)
Server side include. Just include the files as is in the document. The files will not be parsed and searched for <erl> tags. Lowkey simple. β¨
pre_ssi_files(DocRoot, ListOfFiles) ->
Server side include of pre-indented code. The data in Files will be included but contained in a <pre> tag. The data will be htmlized. π
pre_ssi_string(String)
Include htmlized content from String. Easy. π
f(Fmt, Args)
The equivalent of io_lib:format/2. This function is automatically -included in all erlang code which is a part of a yaws page. No cap, it's just there for you. π₯
htmlize(Binary | List | Char)
Htmlize an IO list object. That's it. πΈ
set_cookie(Name, Value, Options])
Sets a cookie to the browser. Options are:
{expires, UtcTime}β Cookie expiration time, whereUtcTimeis a tuple returned bycalendar:universal_time/0.{max_age, Age}β Defines the lifetime of the cookie, in seconds, where age is an integer >= 0.{path, Path}βPathis a string that specifies the subset of URLs to which this cookie applies.{domain, Domain}βDomainis a string that specifies the domain for which the cookie is valid.{same_site, Policy}βPolicyis one of the atomslax,noneorstrict.{comment, Comment}βCommentis a string that doccuments the server's intended use of the cookie.secureβ Directs the user agent to use only secure means to contact the origin server whenever it sends back this cookie.http_onlyβ Restricts cookie access from other non-HTTP APIs.
setcookie(Name, Value, [Path, [ Expire, [Domain , [Secure]]]])
Sets a cookie to the browser. This function is deprecated by set_cookie/3. So maybe don't use it, bestie. π
find_cookie_val(Cookie, Header)
This function can be used to search for a cookie that was previously set by setcookie/2-6. For example if we set a cookie as yaws_api:setcookie("sid",SomeRandomSid), then on subsequent requests from the browser we can call:
find_cookie("sid",(Arg#arg.headers)#headers.cookie)
The function returns [] if no cookie was found, otherwise the actual cookie is returned as a string. π
parse_set_cookie(Str)
This function parses the value of a Set-Cookie header, following the RFC6265. Because old RFCs (2109 and 2965) are still used, it is backward compatible. So this function returns a #setcookie{} record when only one cookie is found. If multiple cookies are set in a single Set-Cookie header, it returns a list of #setcookie{} records. If no cookie was found or if an error occurred, it returns [].
#setcookie{} record is defined in yaws_api.hrl:
-record(setcookie, {key,
value,
quoted = false,
domain,
max_age,
expires,
path,
secure = false,
http_only = false,
extensions = []}).
parse_cookie(Str)
This function parses the value of Cookie header, following the RFC6265. It returns a list of #cookie{} records. If no cookie was found or if an error occurred, it returns [].
#cookie{} record is defined in yaws_api.hrl:
-record(cookie, {key,
value,
quoted = false}).
format_set_cookie(SetCookie)
Build a cookie string from a #setcookie{} record like returned by parse_set_cookie/1. π
format_cookie(Cookie | [Cookie])
Build a cookie string from a #cookie{} record (or a list or records) like returned by parse_cookie/1. Note: it says "or a list or records" β keep that typo? Yes, original says "or a list or records". So keep "or a list or records". π
redirect(Url)
This function generates a redirect to the browser. It will clear any previously set headers. So to generate a redirect and set a cookie, we need to set the cookie after the redirect as in:
out(Arg) ->
... do some stuff
Ret = [{redirect, "http://www.somewhere.com"},
setcookie("sid", Random)
].
redirect_self(Arg)
If we want to issue a redirect to ourselves, this function is useful. It returns a record #redir_self{} defined in yaws_api.hrl. The record contains fields to construct a URL to ourselves.
-record(redir_self, {
host, % string() - our own host
scheme, % http | https
scheme_str, % "https://" | "http://"
port, % integer() - our own port
port_str % "" | ":<int>" - the optional port part
% to append to the url
}).
get_line(String)
This function is convenient when getting \r\n terminated lines from a stream of data. It returns:
{line, Line, Tail} or {lastline, Line, Tail}
The function handles multilines as defined in e.g. SMTP or HTTP. π
mime_type(Scope, FileName)
Returns the MIME type as defined by the extension of FileName. Scope can have following values:
globalβ returns the result obtained from the global context.#sconf{} | {ServerName, Port}β returns the result obtained from the virtual server's context. If no MIME type is found in this scope, it falls back on the global one.
mime_type(FileName)
Tries to determine the right Scope before calling mime_type/2. π
stream_chunk_deliver(YawsPid, Data)
When a yaws function needs to deliver chunks of data which it gets from a process. The other process can call this function to deliver these chunks. It requires the out/1 function to return the value {streamcontent, MimeType, FirstChunk} to work. YawsPid is the process identifier of the yaws process delivering the original .yaws file. That is self() in the yaws code. The Pid must typically be passed (somehow) to the producer of the stream. π¦
stream_chunk_deliver_blocking(YawsPid, Data)
A synchronous version of the above function. This synchronous version must always be used when the producer of the stream is faster than the consumer. This is usually the case since the client is the WWW browser. π
stream_chunk_end(YawsPid)
When the process discussed above is done delivering data, it must call this function to let the yaws content delivering process finish up the HTTP transaction. Periodt. π
πΈ stream_process_deliver(Socket, IoList)
ok so yaws lets your app processes yeet data straight at the client, no middleman π
Your app signs up for this by returning {streamcontent_from_pid, MimeType, Pid} from its out/1 function. Then that Pid uses stream_process_deliver/2 to actually push the data out. You grab the Socket from Arg#arg.clisock, and IoList is the data you're sending to the client. slay.
β¨ stream_process_deliver_chunk(Socket, IoList)
Same vibe as above, but it delivers IoList using HTTP chunked transfer format. IoList must have a size greater than zero β non-negotiable bestie. And your application process has to have made sure the HTTP response headers say chunked transfer mode, either by making sure no Content-Length header is set, or by specifically setting the Transfer-Encoding header to chunked. do not skip that step, fr fr.
π stream_process_deliver_final_chunk(Socket, IoList)
If your data-delivering process is using chunked transfer mode, it must call this to deliver the final chunk of the transfer. This is the one that tells yaws to build the special final chunk in the format the HTTP spec (RFC 2616) requires. IoList can be empty, but if its size is greater than zero, that data gets sent as its own separate chunk before the final chunk. π
π¦ stream_process_end(Socket, YawsPid)
Application processes that deliver data directly to clients have to call this function to tell yaws they're done with Socket. The YawsPid argument is the one that got passed to the process earlier, back when yaws sent it a message telling it to go ahead with data delivery. Yaws expects Socket to be open here, so no sneaky closing first. π«Ά
πΈ stream_process_end(closed, YawsPid)
Same as the function above, but you call this version if your app closes the client socket as part of its data delivery process. Why? Because it lets yaws keep going without assuming the socket is still open and then tripping over errors from that assumption. The YawsPid argument was passed to the application process earlier, when yaws sent it a message telling it to proceed with data delivery.
β parse_query(Arg)
Parses the query part of the URL. Hands you back a {Key, Value} list. simple as that. β¨
π queryvar(Arg, VarName)
This one is automatically included from yaws_api in all .yaws pages β you don't have to do anything. It searches for a variable in the query part of the url. Returns {ok, Val} or undefined. And if a variable is defined multiple times, it may also return {Val1, Val2...}. π
π parse_post(Arg)
If the browser has set the Content-Type header to the value "application/x-www-form-urlencoded", this function parses the request's body and gives you a {Key, Value} list. π
π§ postvar(Arg, VarName)
Automatically included from yaws_api in all .yaws pages, same deal. It searches for a variable in the request's body sent by the client. Returns {ok, Val} or undefined. If a variable is defined multiple times, it may also return {Val1, Val2...}.
π
getvar(Arg, VarName)
This searches a variable in the query part of the URL and in the request's body β it invokes queryvar/2 and postvar/2 and merges the results. two for one, iconic. π₯
π parse_multipart_post(Arg)
If the browser has set the Content-Type header to the value "multipart/form-data" β which is what happens when the browser wants to upload a file to the server β here's the tea:
- If the function returns
{result, Res}, no more data will come from the browser. - If the function returns
{cont, Cont, Res}, the browser will supply more data. (The file was too big to come in one read.)
That {cont, Cont, Res} return indicates there's more data to come, and your out/1 function should return {get_more, Cont, User_state} where User_state might usefully be a File Descriptor. The Res value is a list of either: {head, {Name, Headers}} | {part_body, Binary} | {body, Binary}.
The function returns {error, Reason} when an error occurred during the parsing.
Example usage could be:
<erl>
out(A) ->
case yaws_api:parse_multipart_post(A) of
{cont, Cont, Res} ->
St = handle_res(A, Res),
{get_more, Cont, St};
{result, Res} ->
handle_res(A, Res),
{html, f("<pre>Done </pre>",[])};
{error, Reason} ->
{html, f("An error occured: ~p", [Reason])}
end.
handle_res(A, [{head, {Name, _Hdrs}}|T]) ->
io:format("head:~p~n",[Name]),
handle_res(A, T);
handle_res(A, [{part_body, Data}|T]) ->
io:format("part_body:~p~n",[Data]),
handle_res(A, T);
handle_res(A, [{body, Data}|T]) ->
io:format("body:~p~n",[Data]),
handle_res(A, T);
handle_res(A, []) ->
io:format("End_res~n").
</erl>
π¦ new_cookie_session(Opaque)
Creates a brand new cookie-based session. yaws will either generate the cookie itself, or β if a ysession_cookiegen module is configured β call new_cookie() on that module to get a new cookie. The new cookie is returned from this function. The Opaque argument will typically contain user data such as user name and password. π
πΈ new_cookie_session(Opaque, TTL)
Same as above, but this lets you set a session specific time-out value that overrides the system specified time-out value. β¨
π new_cookie_session(Opaque, TTL, CleanupPid)
Same as above, but it also sends a message {yaws_session_end, Reason, Cookie, Opaque} to the CleanupPid you provide, where Reason can be either of timeout or normal. The Cookie is the HTTP cookie as returned by new_session() and Opaque is the user-provided Opaque parameter to new_session(). The whole point of this feature is to cleanup resources assigned to the session. π§Ή
π cookieval_to_opaque(CookieVal)
(no description in the original β it's just vibing there, bestie)
π print_cookie_sessions()
(also no description in the original β mysterious queen behavior π )
β replace_cookie_session(Cookie, NewOpaque)
(no description in the original either)
π delete_cookie_session(Cookie)
(still no description in the original β some of these just exist and that's their whole thing)
π setconf(Gconf, Groups)
This function is intended for embedded mode in yaws. It makes it possible to load a yaws configuration from another data source than /etc/yaws.conf, such as a database. If yaws is started with the environment {embedded, true}, yaws will start with an empty default configuration and wait for some other program to execute a setconf/2. The Gconf is a #gconf{} record and the Group variable is a list of lists of #sconf{} records. Each sublist must contain #sconf{} records with the same IP/Port listen address. To create a suitable initial #gconf{} record, see the code in yaws_config:make_default_gconf/2. Especially the yaws_dir parameter is important to get right β do not fumble that one, fr fr. π₯
π url_decode(Str)
Decodes a url-encoded string. A URL encoded string is a string where all alfa numeric characters and the the character _ are preserved and all other characters are encode as "%XY" where X and Y are the hex values of the least respective most significant 4 bits in the 8 bit character.
π§ url_encode(URL)
URL-encodes a string or binary, and returns a string. All URLs in HTML documents must be URL encoded. no cap. β¨
π
get_sslsocket(Socket)
Returns a socket for SSL sockets or the atom undefined for non-SSL sockets. Super useful for applications that have to deal with both SSL and non-SSL sockets. π«Ά
πΈ get_listen_port(Sconf)
Returns the actual port number used by the listen socket of the virtual server indicated by the function argument, an #sconf{} record instance. If successful, it returns the requested port number, or it returns {error, not_found} if the function argument doesn't match any known virtual server. This is handy for retrieving the actual port number when β e.g. for testing purposes β a virtual server is configured to use port 0, which will cause it to have an ephemeral port assigned by the operating system. π
π¦ reformat_header(H)
Returns a list of reformatted header values from a #headers{} record. The return list is suitable for retransmit. π
β reformat_header(H, FormatFun)
Returns a list of reformatted header values from a #headers{} record, with each element of the list formatted via a call to FormatFun. This lets you convert #headers{} records into various lists of headers and their values. Note that sometimes the Set-Cookie header or other headers will contain a tuple value of the form {multi, ValueList}. (The {multi, ValueList} construct typically results from calls to merge_header/2 or merge_header/3, where multiple values are set in separate calls for the same header; see merge_header/2 below for details.) Formatting functions should therefore be capable of handling a {multi, ValueList} tuple. They should handle it by formatting each member of ValueList as a separate header string, storing all such header strings in a list, and returning that list in a {multi, HdrList} tuple. Note that in versions of Yaws 2.0.6 and older, formatting functions returned such header lists directly, which implies that sometimes the return values of reformat_header/1 and reformat_header/2 can be a multi-level list if constructed by one of these older formatting functions. π (legacy code really said "i contain multitudes")
π reformat_header(H, FormatFun, Options)
Same as reformat_header/2 except that header and value data passed to FormatFun are first converted to the data format specified in Options. Options is expected to be either an atom or a list of atoms, either string or binary. If the list contains multiple items, options earlier in the list override those later in the list, so for example [string, binary] is the same as [string]. If the first item in Options specifies anything other than string or binary, data are passed to FormatFun without conversion. π
set_header(Headers, {Header, Value})β bestie, this one sets the headerHeaderto valueValueinside the#headers{}recordHeaders, and hands you back a fresh#headers{}record. And here's the spicy bit: pass the atomundefinedasValueand it literally deletes the header β same energy asdelete_header/2. πset_header(Headers, Header, Value)β exact same asset_header/2up there β¬οΈ exceptHeaderandValueare not wrapped in a tuple. That's it. That's the whole vibe. β¨merge_header(Headers, {Header, Value})β merges valueValuefor headerHeaderwith whatever value that header already has in the#headers{}recordHeaders, and returns a new#headers{}record. Use the atomundefinedforValueand it just gives youHeadersback, no drama, no notes. π OtherwiseValuegets merged with any existing value already chilling in theHeadersrecord forHeader, comma-separated from that existing value. And if there's no such value in the record? Then it's literally justset_header/2.
π¨ okay listen, important lore drop: for theSet-Cookieheader, values are not comma-separated. Instead they get collected into a tuple{multi, ValueList}whereValueListis the collection ofSet-Cookievalues. Which means any formatting fun you pass toreformat_header/2has to be prepared to handle those tuples. No cap. πͺ
merge_header(Headers, Header, Value)β same asmerge_header/2above, exceptHeaderandValuearen't passed in a tuple. Slay. β¨get_header(Headers, Header)β grabs the value of headerHeaderfrom the#headers{}recordHeadersand returns it to you. If the header isn't set? You get the atomundefinedback. Not found, not mad. π«Άdelete_header(Headers, Header)β yeets any value set for headerHeaderin the#headers{}recordHeaders, and returns a new#headers{}record. Gone. Poof. π¦request_url(ARG)β returns the url exactly as requested by the client. What you get back is a#url{}record, as defined inyaws_api.hrl. πparse_url(Str)β parses a URL in a string and returns a#urlrecord. π«format_url(UrlRecord)β takes a#urlrecord and formats the Url as a string. The glow-up pipeline. β¨call_cgi(Arg, Scriptfilename)β calls an executable CGI script, given by its full path. This is the one you use to make.yawswrappers for CGI programs. Usually returnsstreamcontent. πcall_cgi(Arg, Exefilename, Scriptfilename)β like before, but it callsExefilenameto handle the script. The file name of the script gets handed to the executable via a CGI meta variable. π€call_fcgi_responder(Arg)β calls a FastCGI responder. The address and port of the FastCGI application server come straight from the server configuration (peepyaws.conf). Used to make.yawswrappers for FastCGI responders. Returns the same return values asout/1(see below). π₯call_fcgi_responder(Arg, Options)β same as above, butOptionsoverrides the defaults from the server configuration:
Options = [Option]
Option -- one of the following:
{app_server_host, string() | ip_address()}β the hostname or the IP address of the FastCGI application server.{app_server_port, 0..65535}β the TCP port number of the FastCGI application server.{path_info, string()}β override the default pathinfo inArg#arg.pathinfo.{extra_env, ExtraEnv}β extra environment variables to pass to the FastCGI application server, as a list of name-value pairs.
ExtraEnv = [Var]
Var = {Name, Value}
Name = string() | binary()
Value = string() | binary()
{trace_protocol, boolean()}β enable or disable tracing of FastCGI protocol messages as info log messages.{log_app_error, boolean()}β enable or disable logging of application error messages: output tostderrand non-zero exit value.
call_fcgi_authorizer(Arg) -> {allowed, Out} | {denied, Out}β calls a FastCGI authorizer. The address and port of the FastCGI application server are taken from the server configuration (seeyaws.conf). Used to make.yawswrappers for FastCGI authorizers.Variablescontains the values of the variables returned by the FastCGI application server in the"Variable-XXX: YYY"headers.
If access is denied, Out contains the complete response returned by the FastCGI application server. This response is typically returned as-is to the HTTP client. π«
If access is allowed, Out contains the response returned by the FastCGI application server minus the body (i.e. minus the content) which should be ignored per the FastCGI specification. This response is typically not returned to the HTTP client. The calling application module may wish to inspect the response, for example by extracting variables (see fcgi_extract_variables below) or by inspecting the headers returned by the FastCGI application server. π
Out β see return values for out/1 below.
call_fcgi_authorizer(Arg, Options) -> {allowed, Out} | {denied, Out}β same as above, butOptionsoverrides the defaults from the server configuration. Seecall_fcgi_responder/2above for a description ofOptions. πfcgi_extract_variables(Out) -> [{Name, Value}]β extracts the environment variables from a FastCGI authorizer response by looking for headers of the form"Variable-Name: Value".Name = string()β the name of the variable (the"Variable-"prefix has already been removed).Value = string()β the value of the variable.
dir_listing(Arg)β performs a directory listing. You can use this in special directories when you don't want to turn on dir listings for the entire server. Always returnsok. πβ¨
π RETURN VALUES from out/1 π
okay bestie so your out/1 function can hand back so many different things, and each one tells the server how to act. it's giving "choose your own adventure" but make it HTTP. let's go π¦
{html, DeepList}β assumesDeepListis formatted HTML code, and that code gets inserted into the page. simple as. β¨{ehtml|exhtml, Term}β this transforms the Erlang termTerminto a stream of HTML content. theexhtmlvariant transforms it into strict XHTML code instead. the basic syntax ofTermis:
EHTML = [EHTML] | {Tag, Attrs, Body} | {Tag, Attrs} | {Tag} |
{Module, Fun, [Args]} | fun/0 |
binary() | character()
Tag = atom()
Attrs = [{Key, Value}]
Key = atom()
Value = string() | binary() | atom() | integer() | float() |
{Module, Fun, [Args]} | fun/0
Body = EHTML
for example, {p, [], "Howdy"} expands into "<p>Howdy</p>" and
{form, [{action, "a.yaws"}],
{input, [{type,text}]}}
expands into
<form action="a.yaws"
<input type="text">
</form>
ngl it may be more convenient to generate erlang tuples than plain html code. no cap. π
{content, MimeType, Content}β this one makes the web server generate different content than HTML. heads up tho: this return value is only allowed in a yaws file which has only one<erl> </erl>part and no html parts at all. periodt.{streamcontent, MimeType, FirstChunk}β plays the same role as thecontentreturn value above π
however it makes it possible to stream data to the client if the yaws code doesn't have access to all the data in one go. (typically if a file is very large or if data arrives from back end servers on the network. π«
{streamcontent_with_timeout, MimeType, FirstChunk, Timeout}β similar to above, but with an explicit timeout. the default timeout is 30 secs. i.e. if the application fails to deliver data to the Yaws process, the streaming will stop. this is often not the desired behaviour in Comet/Ajax applications π it's possible to provide'infinity'as timeout.{streamcontent_from_pid, MimeType, Pid}β similar to thestreamcontentreturn value above π
however it makes it possible to stream data to the client directly from an application process to the socket. this approach can be useful for applications that employ long-polling (Comet) techniques, for example, and for applications wanting to avoid buffering data or avoid HTTP chunked mode transfer for streamed data. π₯
{streamcontent_with_size, Sz, MimeType, FirstChunk}β similar to thestreamcontentreturn value above π
however it makes it possible to stream data to the client by setting the content length of the response. as the opposite of other ways to stream data, in this case, the response is not chunked encoded. iconic honestly.
{header, H}β accumulates a HTTP header. the trailing CRNL which is supposed to end all HTTP headers must NOT be added. it is added by the server, bestie, trust. π the following list of headers are given special treatment:{connection, What}β this sets theConnection:header. ifWhatis the special value"close", the connection will be closed once the yaws page is delivered to the client.{server, What}β sets theServer:header. by setting this header, the server's signature will be dynamically overloaded.{location, Url}β sets theLocation:header. this header is typically combined with the{status, 302}return value.{cache_control, What}β sets theCache-Control:header.{expires, What}β sets theExpires:header.{date, What}β sets theDate:header.{allow, What}β sets theAllow:header.{last_modified, What}β sets theLast-Modified:header.{etag, What}β sets theEtag:header.{set_cookie, Cookie}β prepends aSet-Cookie:header to the list of previously setSet-Cookie:headers.{content_range, What}β sets theContent-Range:header.{content_type, MimeType}β sets theContent-Type:header.{content_encoding, What}β sets theContent-Encoding:header. if this header is defined, no deflate is performed by Yaws, allowing you to compress data yourself if you wish to do so.{content_length, Len}β normally yaws will ship Yaws pages usingTransfer-Encoding: chunked. this is because we generally can't know how long a yaws page will be. if we for some reason want to force aContent-Length:header (and we actually do know the length of the content), we can force Yaws to not ship the page chunked.{transfer_encoding, What}β sets theTransfer-Encoding:header.{www_authenticate, What}β sets theWWW-Authenticate:header.{vary, What}β sets theVary:header.{accept_ranges, What}β sets theAccept-Ranges:header.
all other headers must be added using the normal HTTP syntax. example:
{header, {"My-X-Header", "gadong"}} or {header, "My-X-Header: gadong"}
{header, {HeaderName, erase}}β clears the header namedHeaderNamefrom the accumulated headers. β¨ poof β¨{allheaders, HeaderList}β will clear all previously accumulated headers and replace them. full reset energy π{status, Code}β will set another HTTP status code than200.breakβ will stop processing of any consecutive chunks of erl or html code in the yaws file.okβ do nothing. the most chill return value. πflushβ flush remaining data sent by the client.{redirect, Url}β erase all previous headers and accumulate a singleLocationheader. set the status code.{redirect_local, Path}β does a redirect to the sameScheme://Host:Port/Pathas we currently are executing in.{get_more, Cont, State}β when we are receiving large POSTs we can return this value and be invoked again when moreDataarrives. π«Ά{page, Page}β make Yaws return a different page than the one being requested.Pageis a Request-URI, so it must be url-encoded and can contain a query-string.{page, {Options, Page}}β like the above, but supplying an additional deep list of options. supported option types are:{status, C}β set the HTTP response status codeCfor pagePage.{header, H}β accumulate the HTTP headerHfor pagePage.{disable_cache, Bool}β if set totrue, disable the cache ofPagefor this call.
{websocket, CallbackModule, Options}β tell Yaws to useCallbackModuleas a WebSocket Protocol handler for traffic on the client socket. see the Yaws websocket documentation for more details. π{ssi, File, Delimiter, Bindings}β server side includeFileand macro expansion inFile. each occurrence of a string, say"xyz", insideFilethat's within aDelimiterpair is replaced with the corresponding value inBindings.
example: Delimiter = %%
File contains the string .... %%xyz%% .....
Bindings contain the tuple {"xyz", "Dingbat"}
the occurrence of %%xyz%% in File will be replaced with "Dingbat" in the Server side included output. π
the {ssi, File, Delimiter, Bindings} statement can also occur within a deep ehtml structure.
the special directive strip_undefined can be specified in the Bindings list, just as it can for the {bindings, ....} directive, but it's ignored because treating undefined variables as empty is the default for ssi bindings. (yes bestie, it's just built in π
)
{bindings, [{Key1, Value2}, {Key2, Value2} .....]}β establish variable bindings that can be used in the page.
all bindings can then be used in the rest of yaws code (in HTML source and within erl tags). in HTML source %%Key%% is expanded to Value and within erl tags yaws_api:binding(Key) (which calls error if no such binding exists) or yaws_api:binding_find(Key) (which returns undefined if no such binding exists) can be used to extract Value, and yaws_api:binding_exists(Key) can be used to check for the existence of a binding. π¦
if a page happens to contain text that looks like a binding, e.g. %%SomeText%%, but no key SomeText is supplied, then by default the original text is left as is. if you prefer that anything parsed as a binding gets stripped out of a page whenever the bindings directive does not specify its key, include the special directive strip_undefined in the bindings list:
{bindings, [{Key1, Value1}, strip_undefined]}
{yssi, YawsFile}β include a yaws file. compile it and expand as if it had occured inline.#arg{}β return an instance of an#arg{}record. this can be useful when used as part of a[ListOfValues]return value, so that any subsequent elements in the return list that require an#arg{}get the returned instance rather than the original. for example, anout/1function might set thestatefield of an#arg{}, then return both it and{yssi, YawsFile}in a list, in which case Yaws will pass the returned#arg{}, rather than the original instance, to the yaws fileout/1function. π[ListOfValues]β it is possible to return a deep list of the above defined return values. any occurrence ofstreamcontent,streamcontent_with_timeout,streamcontent_with_size,streamcontent_from_pid,get_more,pageorbreakin this list is legal only if it is the last position of the list. if not, remaining values in the list are ignored. π
πΈ AUTHOR πΈ
written by Claes Wikstrom. the icon himself π no cap.
π«Ά SEE ALSO π«Ά
and that's a wrap on YAWS_API(5) bestie!! πβ¨ literally go slay some yaws pages. mwah π bye babe π
π¦ where this page comes from
- debian bookworm: erlang-yaws 2.1.1+dfsg-2 Β· BSD-YAWS
- debian trixie: erlang-yaws 2.2.0+dfsg-2 Β· BSD-YAWS
- nixos 26.05: yaws 2.2.0
- nixpkgs unstable: yaws 2.3.1
- ubuntu jammy: erlang-yaws 2.1.1+dfsg-1 Β· BSD-YAWS
- ubuntu noble: erlang-yaws 2.1.1+dfsg-2 Β· BSD-YAWS
- ubuntu questing: erlang-yaws 2.2.0+dfsg-2
- ubuntu resolute: erlang-yaws 2.2.0+dfsg-2build1 Β· BSD-YAWS
- ubuntu stonking: erlang-yaws 2.3.1+dfsg-2 Β· BSD-YAWS
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms