1YAWS_API(5)                        User API                        YAWS_API(5)
2
3
4

NAME

6       yaws_api - api available to yaws web server programmers
7

SYNOPSIS

9       yaws_api:Function(...)
10
11

DESCRIPTION

13       This  is  the  api available to yaws web server programmers. The Erlang
14       module yaws_api contains a wide variety of functions that can  be  used
15       inside yaws pages.
16
17
18       Each chunk of yaws code is executed while the yaws page is being deliv‐
19       ered from the server. We give a very simple example here  to  show  the
20       basic idea. Imagine the following HTML code:
21
22
23       <html>
24       <body>
25
26       <h1> Header 1</h1>
27
28       <erl>
29       out(Arg) ->
30           {html, "<p> Insert this text into the document"}.
31       </erl>
32
33       </body>
34       </html>
35
36
37
38
39
40       The  out(Arg)  function  is supplied one argument, an #arg{} structure.
41       We have the following relevant record definitions:
42
43
44
45       -record(arg, {
46                 clisock,        % the socket leading to the peer client
47                 client_ip_port, % {ClientIp, ClientPort} tuple
48                 headers,        % headers
49                 req,            % request
50                 orig_req,       % original request
51                 clidata,        % The client data (as a binary in POST requests)
52                 server_path,    % The normalized server path
53                                 % (pre-querystring part of URI)
54                 querydata,      % For URIs of the form ...?querydata
55                                 %  equiv of cgi QUERY_STRING
56                 appmoddata,     % (deprecated - use pathinfo instead) the remainder
57                                 % of the path leading up to the query
58                 docroot,        % Physical base location of data for this request
59                 docroot_mount,  % virtual directory e.g /myapp/ that the docroot
60                                 %  refers to.
61                 fullpath,       % full deep path to yaws file
62                 cont,           % Continuation for chunked multipart uploads
63                 state,          % State for use by users of the out/1 callback
64                 pid,            % pid of the yaws worker process
65                 opaque,         % useful to pass static data
66                 appmod_prepath, % (deprecated - use prepath instead) path in front
67                                 %  of: <appmod><appmoddata>
68                 prepath,        % Path prior to 'dynamic' segment of URI.
69                                 %  ie http://some.host/<prepath>/<script-point>/d/e
70                                 % where <script-point> is an appmod mount point,
71                                 % or .yaws,.php,.cgi,.fcgi etc script file.
72                 pathinfo        % Set to '/d/e' when calling c.yaws for the request
73                                 % http://some.host/a/b/c.yaws/d/e
74                                 %  equiv of cgi PATH_INFO
75                }).
76
77
78       The headers argument is also a record:
79
80       -record(headers, {
81                 connection,
82                 accept,
83                 host,
84                 if_modified_since,
85                 if_match,
86                 if_none_match,
87                 if_range,
88                 if_unmodified_since,
89                 range,
90                 referer,
91                 user_agent,
92                 accept_ranges,
93                 cookie = [],
94                 keep_alive,
95                 location,
96                 content_length,
97                 content_type,
98                 content_encoding,
99                 authorization,
100                 transfer_encoding,
101                 x_forwarded_for,
102                 other = []   % misc other headers
103                }).
104
105
106
107       The out/1 function can use the Arg to generate any content it likes. We
108       have the following functions to aid that generation.
109
110
111

API

113       ssi(DocRoot, ListOfFiles)
114              Server  side  include. Just include the files as is in the docu‐
115              ment. The files will not be parsed and searched for <erl> tags.
116
117
118
119       pre_ssi_files(DocRoot, ListOfFiles) ->
120              Server side include of pre-indented code.   The  data  in  Files
121              will  be included but contained in a <pre> tag. The data will be
122              htmlized.
123
124
125       pre_ssi_string(String)
126              Include htmlized content from String.
127
128
129
130       f(Fmt, Args)
131              The equivalent of io_lib:format/2. This  function  is  automati‐
132              cally  -included  in  all  erlang code which is a part of a yaws
133              page.
134
135
136       htmlize(Binary | List | Char)
137              Htmlize an IO list object.
138
139
140       set_cookie(Name, Value, Options])
141              Sets a cookie to the browser. Options are:
142
143              {expires, UtcTime}  - Cookie expiration time, where UtcTime is
144                                    a tuple returned by calendar:universal_time/0.
145              {max_age, Age}      - Defines the lifetime of the cookie, in seconds,
146                                    where age is an integer >= 0.
147              {path, Path}        - Path is a string that specifies the subset of URLs to
148                                    which this cookie applies.
149              {domain, Domain}    - Domain is a string that specifies the domain for which
150                                    the cookie is valid.
151              {comment, Comment}  - Comment is a string that doccuments the server's
152                                    intended use of the cookie.
153              secure              - Directs the user agent to use only secure means to
154                                    contact the origin server whenever it sends back this
155                                    cookie.
156              http_only           - Restricts cookie access from other non-HTTP APIs.
157
158
159
160       setcookie(Name, Value, [Path, [ Expire, [Domain , [Secure]]]])
161              Sets a cookie to the browser. This  function  is  deprecated  by
162              set_cookie/3.
163
164
165       find_cookie_val(Cookie, Header)
166              This function can be used to search for a cookie that was previ‐
167              ously set by setcookie/2-6. For example if we set  a  cookie  as
168              yaws_api:setcookie("sid",SomeRandomSid),   then   on  subsequent
169              requests     from     the     browser     we      can      call:
170              find_cookie("sid",(Arg#arg.headers)#headers.cookie)
171
172              The  function  returns  [] if no cookie was found, otherwise the
173              actual cookie is returned as a string.
174
175
176       parse_set_cookie(Str)
177              This function parses the value of a Set-Cookie header, following
178              the RFC6265. Because old RFCs (2109 and 2965) are still used, it
179              is backward compatible. So this function returns a  #setcookie{}
180              record  when  only  one cookie is found. If multiple cookies are
181              set in a single Set-Cookie header, it returns a  list  of  #set‐
182              cookie{}  records.  If  no  cookie  was  found  or  if  an error
183              occurred, it returns [].
184
185              #setcookie{} record is defined in yaws_api.hrl:
186
187              -record(setcookie, {key,
188                                  value,
189                                  quoted = false,
190                                  domain,
191                                  max_age,
192                                  expires,
193                                  path,
194                                  secure = false,
195                                  http_only = false,
196                                  extensions = []}).
197
198
199
200       parse_cookie(Str)
201              This function parses the value of Cookie header,  following  the
202              RFC6265.  It  returns  a list of #cookie{} records. If no cookie
203              was found or if an error occurred, it returns [].
204
205              #cookie{} record is defined in yaws_api.hrl:
206
207              -record(cookie, {key,
208                               value,
209                               quoted = false}).
210
211
212
213       format_set_cookie(SetCookie)
214              Build a cookie string from a #setcookie{} record  like  returned
215              by parse_set_cookie/1.
216
217
218       format_cookie(Cookie | [Cookie])
219              Build  a  cookie  string  from  a #cookie{} record (or a list or
220              records) like returned by parse_cookie/1.
221
222
223       redirect(Url)
224              This function generates a redirect  to  the  browser.   It  will
225              clear  any previously set headers. So to generate a redirect and
226              set a cookie, we need to set the cookie after  the  redirect  as
227              in:
228              out(Arg) ->
229                ... do some stuff
230
231                Ret = [{redirect, "http://www.somewhere.com"},
232                        setcookie("sid", Random)
233                      ].
234
235
236
237
238
239       redirect_self(Arg)
240              If  we  want  to issue a redirect to ourselves, this function is
241              useful.  It  returns   a   record   #redir_self{}   defined   in
242              yaws_api.hrl.  The  record contains fields to construct a URL to
243              ourselves.
244
245              -record(redir_self, {
246                        host,        % string() - our own host
247                        scheme,      % http | https
248                        scheme_str,  % "https://"  | "http://"
249                        port,        % integer()  - our own port
250                        port_str     % "" | ":<int>" - the optional port part
251                                     %                 to append to the url
252                       }).
253
254
255
256       get_line(String)
257              This function is convenient when getting \r\n  terminated  lines
258              from a stream of data. It returns:
259
260              {line, Line, Tail} or {lastline, Line, Tail}
261
262              The function handles multilines as defined in e.g. SMTP or HTTP
263
264
265       mime_type(Scope, FileName)
266              Returns  the  MIME type as defined by the extension of FileName.
267              Scope can have following values:
268
269                   global - returns the result obtained from the  global  con‐
270                   text.
271                   #sconf{} | {ServerName, Port} - returns the result obtained
272                   from the virtual server's context. If no MIME type is found
273                   in this scope, it falls back on the global one.
274
275
276       mime_type(FileName)
277              Tries to determine the right Scope before calling mime_type/2.
278
279
280
281       stream_chunk_deliver(YawsPid, Data)
282              When  a  yaws  function needs to deliver chunks of data which it
283              gets from a process. The other process can call this function to
284              deliver  these  chunks. It requires the out/1 function to return
285              the  value  {streamcontent,  MimeType,  FirstChunk}   to   work.
286              YawsPid is the process identifier of the yaws process delivering
287              the original .yaws file. That is self() in the yaws  code.   The
288              Pid  must  typically  be passed (somehow) to the producer of the
289              stream.
290
291
292       stream_chunk_deliver_blocking(YawsPid, Data)
293              A synchronous version of the above  function.  This  synchronous
294              version  must  always be used when the producer of the stream is
295              faster than the consumer. This is usually  the  case  since  the
296              client is the WWW browser.
297
298
299       stream_chunk_end(YawsPid)
300              When  the  process  discussed  above is done delivering data, it
301              must call this function  to  let  the  yaws  content  delivering
302              process finish up the HTTP transaction.
303
304
305       stream_process_deliver(Socket, IoList)
306              Yaws  allows  application  processes to deliver data directly to
307              the client. The application tells yaws about such a  process  by
308              returning {streamcontent_from_pid, MimeType, Pid} from its out/1
309              function. In this case, Pid  uses  the  stream_process_deliver/2
310              function  to  deliver  data  to the client. The application gets
311              Socket from Arg#arg.clisock, and IoList is the data to  be  sent
312              to the client.
313
314
315       stream_process_deliver_chunk(Socket, IoList)
316              Same  as  above  but delivers IoList using HTTP chunked transfer
317              format. IoList must have a size greater than zero. The  applica‐
318              tion process delivering the data will have had to have make sure
319              that the HTTP headers of the response indicate chunked  transfer
320              mode,  either  by ensuring no Content-Length header is set or by
321              specifically setting the Transfer-Encoding header to chunked.
322
323
324       stream_process_deliver_final_chunk(Socket, IoList)
325              If the application process delivering data to  the  client  uses
326              chunked  transfer  mode,  it must call this to deliver the final
327              chunk of the transfer. This tells yaws to create a special final
328              chunk  in  the  format  required  by the HTTP specification (RFC
329              2616). IoList may be empty, but if  its  size  is  greater  than
330              zero,  that  data  will  be  sent as a separate chunk before the
331              final chunk.
332
333
334       stream_process_end(Socket, YawsPid)
335              Application processes delivering data directly to  clients  must
336              call  this  function  to inform yaws that they've finished using
337              Socket. The YawsPid  argument  will  have  been  passed  to  the
338              process  earlier  when yaws sent it a message telling it to pro‐
339              ceed with data delivery. Yaws expects Socket to be open.
340
341
342       stream_process_end(closed, YawsPid)
343              Same as the previous function but the application calls this  if
344              it  closes  the  client  socket  as  part  of  its data delivery
345              process. This allows  yaws  to  continue  without  assuming  the
346              socket is still open and encountering errors due to that assump‐
347              tion. The YawsPid argument will have been passed to the applica‐
348              tion  process  earlier when yaws sent it a message telling it to
349              proceed with data delivery.
350
351
352       parse_query(Arg)
353              This function will parse the query part  of  the  URL.  It  will
354              return a {Key, Value} list.
355
356
357       queryvar(Arg, VarName)
358              This  function  is  automatically  included from yaws_api in all
359              .yaws pages. It is used to search for a variable in  the  query‐
360              part  of  the url. Returns {ok, Val} or undefined. If a variable
361              is defined multiple times, the function may also  return  {Val1,
362              Val2...}.
363
364
365       parse_post(Arg)
366              If  the  browser  has  set  the Content-Type header to the value
367              "application/x-www-form-urlencoded", this  function  will  parse
368              the request's body. It will return a {Key, Value} list.
369
370
371       postvar(Arg, VarName)
372              This  function  is  automatically  included from yaws_api in all
373              .yaws pages. It  is  used  to  search  for  a  variable  in  the
374              request's  body  sent  by the client. Returns {ok, Val} or unde‐
375              fined. If a variable is defined multiple times, the function may
376              also return {Val1, Val2...}.
377
378
379       getvar(Arg, VarName)
380              This  function is used to search a variable in the query part of
381              the URL and in the request's body.  it  invokes  queryvar/2  and
382              postvar/2 and merges the results.
383
384
385
386       parse_multipart_post(Arg)
387              If  the  browser  has  set  the Content-Type header to the value
388              "multipart/form-data", which is the case when the browser  wants
389              to upload a file to the server the following happens:
390
391              If  the  function  returns  {result, Res} no more data will come
392              from the browser.
393
394              If the function returns {cont, Cont, Res} the browser will  sup‐
395              ply more data. (The file was too big to come in one read)
396
397              This  indicates  that  there  is more data to come and the out/1
398              function  should  return  {get_more,  Cont,  User_state}   where
399              User_state  might  usefully be a File Descriptor.  The Res value
400              is a list of  either:  {head,  {Name,  Headers}}  |  {part_body,
401              Binary} | {body, Binary}
402
403              The function returns {error, Reason} when an error occurred dur‐
404              ing the parsing.
405
406
407              Example usage could be:
408               <erl>
409
410               out(A) ->
411                      case yaws_api:parse_multipart_post(A) of
412                           {cont, Cont, Res} ->
413                                  St = handle_res(A, Res),
414                                  {get_more, Cont, St};
415                           {result, Res} ->
416                                  handle_res(A, Res),
417                                  {html, f("<pre>Done </pre>",[])};
418                           {error, Reason} ->
419                                  {html, f("An error occured: ~p", [Reason])}
420                      end.
421
422               handle_res(A, [{head, {Name, _Hdrs}}|T]) ->
423                    io:format("head:~p~n",[Name]),
424                    handle_res(A, T);
425               handle_res(A, [{part_body, Data}|T]) ->
426                    io:format("part_body:~p~n",[Data]),
427                    handle_res(A, T);
428               handle_res(A, [{body, Data}|T]) ->
429                    io:format("body:~p~n",[Data]),
430                    handle_res(A, T);
431               handle_res(A, []) ->
432                    io:format("End_res~n").
433
434               </erl>
435
436
437
438
439
440       new_cookie_session(Opaque)
441              Create a new cookie-based session. Yaws will either generate the
442              cookie  itself or, if a ysession_cookiegen module is configured,
443              call new_cookie() on that module to get a new  cookie.  The  new
444              cookie  is returned from this function. The Opaque argument will
445              typically contain user data such as user name and password
446
447
448       new_cookie_session(Opaque, TTL)
449              As above, but allows to set a session specific  time-out  value,
450              overriding the system specified time-out value.
451
452
453       new_cookie_session(Opaque, TTL, CleanupPid)
454              As  above,  but  also sends a message {yaws_session_end, Reason,
455              Cookie, Opaque} to the provided CleanupPid where Reason  can  be
456              either  of  timeout  or normal. The Cookie is the HTTP cookie as
457              returned by new_session() and Opaque is the user-provided Opaque
458              parameter  to  new_session().   The purpose of the feature is to
459              cleanup resources assigned to the session.
460
461
462
463       cookieval_to_opaque(CookieVal)
464
465
466       print_cookie_sessions()
467
468
469
470       replace_cookie_session(Cookie, NewOpaque)
471
472
473       delete_cookie_session(Cookie)
474
475
476
477       setconf(Gconf, Groups)
478              This function is intended for embedded mode in yaws. It makes it
479              possible  to  load a yaws configuration from another data source
480              than /etc/yaws.conf, such as a database.   If  yaws  is  started
481              with  the  environment {embedded, true}, yaws will start with an
482              empty default configuration, and wait for some other program  to
483              execute a setconf/2 The Gconf is a #gconf{} record and the Group
484              variable is a list of lists of #sconf{}  records.  Each  sublist
485              must  contain  #sconf{}  records  with  the  same IP/Port listen
486              address.  To create a suitable initial #gconf{} record  see  the
487              code   in   yaws_config:make_default_gconf/2.   Especially   the
488              yaws_dir parameter is important to get right.
489
490
491
492       url_decode(Str)
493              Decode url-encoded string. A URL  encoded  string  is  a  string
494              where  all  alfa  numeric characters and the the character _ are
495              preserved and all other characters are encode as "%XY"  where  X
496              and  Y  are the hex values of the least respective most signifi‐
497              cant 4 bits in the 8 bit character.
498
499
500       url_encode(Str)
501              Url-encodes a string. All URLs in HTML  documents  must  be  URL
502              encoded.
503
504
505       get_sslsocket(Socket)
506              Returns  a socket for SSL sockets or the atom undefined for non-
507              SSL sockets. Useful for applications that have to deal with both
508              SSL and non-SSL sockets.
509
510
511       get_listen_port(Sconf)
512              Return  the  actual port number used by the listen socket of the
513              virtual server indicated by the function argument,  an  #sconf{}
514              record  instance. If successful, returns the requested port num‐
515              ber, or returns {error, not_found} if the function argument does
516              not  match any known virtual server. This function is useful for
517              retrieving the actual port number when, e.g.  for  testing  pur‐
518              poses,  a virtual server is configured to use port 0, which will
519              cause it to have an ephemeral port  assigned  by  the  operating
520              system.
521
522
523       reformat_header(H)
524              Returns  a  list  of reformatted header values from a #headers{}
525              record. The return list is suitable for retransmit.
526
527
528       reformat_header(H, FormatFun)
529              Returns a list of reformatted header values  from  a  #headers{}
530              record,  with  each  element of the list formatted via a call to
531              FormatFun. This enables converting #headers{} records into vari‐
532              ous  lists  of headers and their values. Note that sometimes the
533              Set-Cookie header will contain a tuple value of the form {multi,
534              ValueList}  —  see merge_header/2 below for details — so format‐
535              ting functions should be prepared to handle such a  tuple.  They
536              should  handle  it  by  formatting each member of ValueList as a
537              separate Set-Cookie header, then returning all such header-value
538              pairs  in  a  list.  Note  that  this implies that sometimes the
539              return values of reformat_header/1 and reformat_header/2 can  be
540              a  multi-level  list.  The  {multi, ValueList} construct results
541              only from calls to merge_header/2 or merge_header/3, where  mul‐
542              tiple values are set in separate calls for the same header.
543
544
545       set_header(Headers, {Header, Value})
546              Sets  header  Header  with  value Value in the #headers{} record
547              Headers, and returns a new #headers{}  record.  Using  the  atom
548              undefined  for  Value  effectively  deletes  the header, same as
549              delete_header/2.
550
551
552       set_header(Headers, Header, Value)
553              Same as set_header/2 above, except  Header  and  Value  are  not
554              passed in a tuple.
555
556
557       merge_header(Headers, {Header, Value})
558              Merges value Value for header Header with any existing value for
559              that header in the #headers{} record Headers, and returns a  new
560              #headers{}  record.  Using  the  atom undefined for Value simply
561              returns Headers. Otherwise, Value is merged  with  any  existing
562              value  already  present in the Headers record for header Header,
563              comma-separated from that  existing  value.  If  no  such  value
564              exists  in  the  Headers  record,  the  effect  is  the  same as
565              set_header/2. Note that for the Set-Cookie  header,  values  are
566              not  comma-separated  but  are  instead  collected  into a tuple
567              {multi, ValueList} where ValueList is  the  collection  of  Set-
568              Cookie  values.  This  implies that any formatting fun passed to
569              reformat_header/2 must be prepared to handle such tuples.
570
571
572       merge_header(Headers, Header, Value)
573              Same as merge_header/2 above, except Header and  Value  are  not
574              passed in a tuple.
575
576
577       get_header(Headers, Header)
578              Gets the value of header Header from the #headers{} record Head‐
579              ers and returns it. If the header isn't set, the atom  undefined
580              is returned.
581
582
583       delete_header(Headers, Header)
584              Deletes any value set for header Header in the #headers{} record
585              Headers, and returns a new #headers{} record.
586
587
588       request_url(ARG)
589              Return the url as requested by the client.  Return  value  is  a
590              #url{} record as defined in yaws_api.hrl
591
592
593
594       parse_url(Str)
595              Parse URL in a string, returns a #url record
596
597
598       format_url(UrlRecord)
599              Takes a #url record a formats the Url as a string
600
601
602       call_cgi(Arg, Scriptfilename)
603              Calls an executable CGI script, given by its full path.  Used to
604              make `.yaws' wrappers for CGI programs.  This  function  usually
605              returns streamcontent.
606
607
608       call_cgi(Arg, Exefilename, Scriptfilename)
609              Like  before,  but  calls Exefilename to handle the script.  The
610              file name of the script is handed to the executable  via  a  CGI
611              meta variable.
612
613
614       call_fcgi_responder(Arg)
615              Calls  a FastCGI responder.  The address and port of the FastCGI
616              application server are taken from the server configuration  (see
617              yaws.conf).   Used  to make `.yaws' wrappers for FastCGI respon‐
618              ders.  Returns the same return values as out/1 (see below).
619
620
621       call_fcgi_responder(Arg, Options)
622              Same as above, but  Options  overrides  the  defaults  from  the
623              server configuration:
624
625
626              Options = [Option]
627              Option -- one of the following:
628
629
630              {app_server_host,  string()  | ip_address()} The hostname or the
631              IP address of the FastCGI application server.
632
633              {app_server_port, 0..65535} The TCP port number of  the  FastCGI
634              application server.
635
636              {path_info,    string()}    Override    default    pathinfo   in
637              Arg#arg.pathinfo.
638
639              {extra_env, ExtraEnv} Extra environment variables to  be  passed
640              to  the  FastCGI  application  server,  as  a list of name-value
641              pairs.
642
643
644              ExtraEnv = [Var]
645              Var = {Name, Value}
646              Name = string() | binary()
647              Value = string() | binary()
648
649
650              {trace_protocol, boolean()} Enable or disable tracing of FastCGI
651              protocol messages as info log messages.
652
653              {log_app_error, boolean()} Enable or disable logging of applica‐
654              tion error messages: output to stderr and non-zero exit value.
655
656
657       call_fcgi_authorizer(Arg) -> {allowed, Out} | {denied, Out}
658              Calls a FastCGI authorizer.  The address and port of the FastCGI
659              application  server are taken from the server configuration (see
660              yaws.conf).  Used to make `.yaws' wrappers for FastCGI authoriz‐
661              ers.  Variables contains the values of the variables returned by
662              the FastCGI application server in the "Variable-XXX: YYY"  head‐
663              ers.
664
665              If access is denied, Out contains the complete response returned
666              by the FastCGI application server. This  response  is  typically
667              returned as-is to the HTTP client.
668
669              If  access is allowed, Out contains the response returned by the
670              FastCGI application server minus the body (i.e. minus  the  con‐
671              tent)  which  should  be  ignored per the FastCGI specification.
672              This response is typically not returned to the HTTP client.  The
673              calling application module may wish to inspect the response, for
674              example  by  extracting  variables  (see  fcgi_extract_variables
675              below)  or  by  inspecting  the  headers returned by the FastCGI
676              application server.
677
678
679              Out -- See return values for out/1 below
680
681
682
683       call_fcgi_authorizer(Arg, Options) -> {allowed, Out} | {denied, Out}
684              Same as above, but  Options  overrides  the  defaults  from  the
685              server  configuration.  See  call_fcgi_responder/2  above  for a
686              description of Options.
687
688
689       fcgi_extract_variables(Out) -> [{Name, Value}]
690              Extracts the environment variables  from  a  FastCGI  authorizer
691              response  by  looking  for  headers  of the form "Variable-Name:
692              Value".
693
694
695              Name = string() -- The name of the variable (the "Variable-" prefix
696              has already been removed).
697              Value = string() -- The value of the variable.
698
699
700
701       dir_listing(Arg)
702              Perform a directory listing. Can be used in special  directories
703              when  we  don't  want  to  turn  on  dir listings for the entire
704              server.  Always returns ok.
705
706

RETURN VALUES from out/1

708       The out/1 function can return different values to control the  behavior
709       of the server.
710
711
712       {html, DeepList}
713              This  assumes  that  DeepList  is formatted HTML code.  The code
714              will be inserted in the page.
715
716
717       {ehtml|exhtml, Term}
718              This will transform the erlang term Term into a stream  of  HTML
719              content.  The  exhtml variant transforms into strict XHTML code.
720              The basic syntax of Term is
721
722
723              EHTML = [EHTML] | {Tag, Attrs, Body} | {Tag, Attrs} | {Tag} |
724                      {Module, Fun, [Args]} | fun/0 |
725                      binary() | character()
726              Tag   = atom()
727              Attrs = [{Key, Value}]
728              Key   = atom()
729              Value = string() | binary() | atom() | integer() | float() |
730                      {Module, Fun, [Args]} | fun/0
731              Body  = EHTML
732
733
734
735              For example, {p, [], "Howdy"} expands into "<p>Howdy</p>" and
736
737
738              {form, [{action, "a.yaws"}],
739                 {input, [{type,text}]}}
740
741
742
743              expands into
744
745
746              <form action="a.yaws"
747                <input type="text">
748              </form>
749
750
751              It may be more convenient to generate erlang tuples  than  plain
752              html code.
753
754
755       {content, MimeType, Content}
756              This  function  will make the web server generate different con‐
757              tent than HTML. This return value is only allowed in a yaws file
758              which has only one <erl> </erl> part and no html parts at all.
759
760
761
762       {streamcontent, MimeType, FirstChunk}
763              This  return  value  plays  the  same role as the content return
764              value above.
765
766              However it makes it possible to stream data to the client if the
767              yaws  code doesn't have access to all the data in one go. (Typi‐
768              cally if a file is very large or if data arrives from  back  end
769              servers on the network.
770
771
772       {streamcontent_with_timeout, MimeType, FirstChunk, Timeout}
773              Similar  to  above,  but  with  an explicit timeout. The default
774              timeout is 30 secs. I.e if the application fails to deliver data
775              to  the Yaws process, the streaming will stop. This is often not
776              the desired behaviour in Comet/Ajax applications.  It's possible
777              to provide 'infinity' as timeout.
778
779
780       {streamcontent_from_pid, MimeType, Pid}
781              This  return  value is similar to the streamcontent return value
782              above.
783
784              However it makes it  possible  to  stream  data  to  the  client
785              directly  from  an  application  process  to  the  socket.  This
786              approach can be useful for applications that employ long-polling
787              (Comet) techniques, for example, and for applications wanting to
788              avoid buffering data or avoid HTTP  chunked  mode  transfer  for
789              streamed data.
790
791
792       {streamcontent_with_size, Sz, MimeType, FirstChunk}
793              This  return  value is similar to the streamcontent return value
794              above.
795
796              However it makes it possible to stream data  to  the  client  by
797              setting  the  content length of the response. As the opposite of
798              other ways to stream data, in this case,  the  response  is  not
799              chunked encoded.
800
801
802
803       {header, H}
804              Accumulates  a  HTTP header. The trailing CRNL which is supposed
805              to end all HTTP headers must NOT be added. It is  added  by  the
806              server.   The following list of headers are given special treat‐
807              ment.
808
809              {connection, What}
810
811              This sets the Connection: header. If What is the  special  value
812              "close",  the  connection  will  be closed once the yaws page is
813              delivered to the client.
814
815              {server, What}
816
817              Sets the Server: header. By setting this  header,  the  server's
818              signature will be dynamically overloaded.
819
820              {location, Url}
821
822              Sets  the  Location:  header.  This header is typically combined
823              with the {status, 302} return value.
824
825              {cache_control, What}
826
827              Sets the Cache-Control: header.
828
829              {expires, What}
830
831              Sets the Expires: header.
832
833              {date, What}
834
835              Sets the Date: header.
836
837              {allow, What}
838
839              Sets the Allow: header.
840
841              {last_modified, What}
842
843              Sets the Last-Modified: header.
844
845              {etag, What}
846
847              Sets the Etag: header.
848
849              {set_cookie, Cookie}
850
851              Prepends a Set-Cookie: header to the list of previously set Set-
852              Cookie: headers.
853
854              {content_range, What}
855
856              Sets the Content-Range: header.
857
858              {content_type, MimeType}
859
860              Sets the Content-Type: header.
861
862              {content_encoding, What}
863
864              Sets the Content-Encoding: header. If this header is defined, no
865              deflate is performed by Yaws,  allowing  you  to  compress  data
866              yourself if you wish to do so.
867
868              {content_length, Len}
869
870              Normally  yaws  will  ship  Yaws  pages using Transfer-Encoding:
871              chunked. This is because we generally can't know how long a yaws
872              page  will  be.  If  we for some reason want to force a Content-
873              Length: header (and we actually do know the length of  the  con‐
874              tent, we can force Yaws to not ship the page chunked.
875
876              {transfer_encoding, What}
877
878              Sets the Transfer-Encoding: header.
879
880              {www_authenticate, What}
881
882              Sets the WWW-Authenticate: header.
883
884              {vary, What}
885
886              Sets the Vary: header.
887
888
889              All  other  headers  must be added using the normal HTTP syntax.
890              Example:
891
892              {header, {"My-X-Header", "gadong"}}  or  {header,  "My-X-Header:
893              gadong"}
894
895
896       {header, {HeaderName, erase}}
897              Clears the header named HeaderName from the accumulated headers.
898
899
900       {allheaders, HeaderList}
901              Will clear all previously accumulated headers and replace them.
902
903
904
905       {status, Code}
906              Will set another HTTP status code than 200.
907
908
909
910       break  Will  stop  processing  of any consecutive chunks of erl or html
911              code in the yaws file.
912
913
914       ok     Do nothing.
915
916
917       flush  Flush remaining data sent by the client.
918
919
920
921       {redirect, Url}
922              Erase all previous headers  and  accumulate  a  single  Location
923              header. Set the status code.
924
925
926       {redirect_local, Path}
927              Does  a  redirect to the same Scheme://Host:Port/Path as we cur‐
928              rently are executing in.
929
930
931       {get_more, Cont, State}
932              When we are receiving large POSTs we can return this  value  and
933              be invoked again when more Data arrives.
934
935
936
937       {page, Page}
938
939              Make Yaws returns a different page than the one being requested.
940              Page is a Request-URI, so it must be url-encoded and can contain
941              a query-string.
942
943
944
945       {page, {Options, Page}}
946              Like  the  above,  but  supplying  an  additional  deep  list of
947              options. Supported option types are:
948
949              {status, C} - Set the HTTP response status code C for page Page.
950
951              {header, H} - Accumulate the HTTP header H for page Page.
952
953              {disable_cache, Bool} - if set to true,  disable  the  cache  of
954              Page for this call.
955
956
957       {websocket, CallbackModule, Options}
958              Tell  Yaws to use CallbackModule as a WebSocket Protocol handler
959              for traffic on the client socket. See the Yaws  websocket  docu‐
960              mentation for more details.
961
962
963       {ssi, File, Delimiter, Bindings}
964              Server  side  include  File  and  macro expansion in File.  Each
965              occurrence of a string, say "xyz", inside File that's  within  a
966              Delimiter pair is replaced with the corresponding value in Bind‐
967              ings.
968
969              Example: Delimiter = %%
970
971              File contains the string .... %%xyz%%  .....
972
973              Bindings contain the tuple {"xyz", "Dingbat"}
974
975              The occurrence of %%xyz%% in File will be replaced  with  "Ding‐
976              bat" in the Server side included output.
977
978              The  {ssi,  File,  Delimiter, Bindings} statement can also occur
979              within a deep ehtml structure.
980
981
982
983       {bindings, [{Key1, Value2}, {Key2, Value2} .....]}
984              Establish variable bindings that can be used in the page.
985
986              All bindings can then be used in the rest of yaws code (in  HTML
987              source and within erl tags).  In HTML source %%Key%% is expanded
988              to Value and within erl tags yaws_api:binding(Key) can  be  used
989              to extract Value and yaws_api:binding_exists(Key) can be used to
990              check for the existence of a binding.
991
992
993       {yssi, YawsFile}
994              Include a yaws file. Compile it and expand as if it had  occured
995              inline.
996
997
998       #arg{} Return  an instance of an #arg{} record. This can be useful when
999              used as part of a [ListOfValues] return value, so that any  sub‐
1000              sequent  elements  in the return list that require an #arg{} get
1001              the returned instance rather than the original. For example,  an
1002              out/1  function  might  set  the  state field of an #arg{}, then
1003              return both it and {yssi, YawsFile} in a  list,  in  which  case
1004              Yaws  will  pass  the  returned #arg{}, rather than the original
1005              instance, to the yaws file out/1 function.
1006
1007
1008       [ListOfValues]
1009              It is possible to return a deep list of the above defined return
1010              values.    Any    occurrence    of   streamcontent,   streamcon‐
1011              tent_with_timeout,      streamcontent_with_size,      streamcon‐
1012              tent_from_pid,  get_more,  page  or  break in this list is legal
1013              only if it is the last position of the list. If  not,  remaining
1014              values in the list are ignored.
1015
1016
1017
1018
1019

AUTHOR

1021       Written by Claes Wikstrom
1022

SEE ALSO

1024       yaws.conf(5) erl(1)
1025
1026
1027
1028
1029                                                                   YAWS_API(5)
Impressum