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, the yaws system will set  the
442              cookie.  The  new  random generated cookie is returned from this
443              function. The Opaque argument will typically contain  user  data
444              such as user name and password
445
446
447       new_cookie_session(Opaque, TTL)
448              As  above,  but allows to set a session specific time-out value,
449              overriding the system specified time-out value.
450
451
452       new_cookie_session(Opaque, TTL, CleanupPid)
453              As above, but also sends a  message  {yaws_session_end,  Reason,
454              Cookie,  Opaque}  to  the provided CleanuPid where Reason can be
455              either of timeout or normal. The Cookie is the  HTTP  cookie  as
456              returned  by  new_session()  and the Opaque is the user provided
457              Opaque parameter to new_session().  The purpose of  the  feature
458              is to cleanup resources assigned to the session.
459
460
461
462       cookieval_to_opaque(CookieVal)
463
464
465       print_cookie_sessions()
466
467
468
469       replace_cookie_session(Cookie, NewOpaque)
470
471
472       delete_cookie_session(Cookie)
473
474
475
476       setconf(Gconf, Groups)
477              This function is intended for embedded mode in yaws. It makes it
478              possible to load a yaws configuration from another  data  source
479              than  /etc/yaws.conf,  such  as  a database.  If yaws is started
480              with the environment {embedded, true}, yaws will start  with  an
481              empty  default configuration, and wait for some other program to
482              execute a setconf/2 The Gconf is a #gconf{} record and the Group
483              variable  is  a  list of lists of #sconf{} records. Each sublist
484              must contain #sconf{}  records  with  the  same  IP/Port  listen
485              address.   To  create a suitable initial #gconf{} record see the
486              code   in   yaws_config:make_default_gconf/2.   Especially   the
487              yaws_dir parameter is important to get right.
488
489
490
491       url_decode(Str)
492              Decode  url-encoded  string.  A  URL  encoded string is a string
493              where all alfa numeric characters and the the  character  _  are
494              preserved  and  all other characters are encode as "%XY" where X
495              and Y are the hex values of the least respective  most  signifi‐
496              cant 4 bits in the 8 bit character.
497
498
499       url_encode(Str)
500              Url-encodes  a  string.  All  URLs in HTML documents must be URL
501              encoded.
502
503
504       get_sslsocket(Socket)
505              Returns a socket for SSL sockets or the atom undefined for  non-
506              SSL sockets. Useful for applications that have to deal with both
507              SSL and non-SSL sockets.
508
509
510       get_listen_port(Sconf)
511              Return the actual port number used by the listen socket  of  the
512              virtual  server  indicated by the function argument, an #sconf{}
513              record instance. If successful, returns the requested port  num‐
514              ber, or returns {error, not_found} if the function argument does
515              not match any known virtual server. This function is useful  for
516              retrieving  the  actual  port number when, e.g. for testing pur‐
517              poses, a virtual server is configured to use port 0, which  will
518              cause  it  to  have  an ephemeral port assigned by the operating
519              system.
520
521
522       reformat_header(H)
523              Returns a list of reformatted header values  from  a  #headers{}
524              record. The return list is suitable for retransmit.
525
526
527       reformat_header(H, FormatFun)
528              Returns  a  list  of reformatted header values from a #headers{}
529              record, with each element of the list formatted via  a  call  to
530              FormatFun. This enables converting #headers{} records into vari‐
531              ous lists of headers and their values. Note that  sometimes  the
532              Set-Cookie header will contain a tuple value of the form {multi,
533              ValueList} — see merge_header/2 below for details —  so  format‐
534              ting  functions  should be prepared to handle such a tuple. They
535              should handle it by formatting each member  of  ValueList  as  a
536              separate Set-Cookie header, then returning all such header-value
537              pairs in a list. Note  that  this  implies  that  sometimes  the
538              return  values of reformat_header/1 and reformat_header/2 can be
539              a multi-level list. The  {multi,  ValueList}  construct  results
540              only  from calls to merge_header/2 or merge_header/3, where mul‐
541              tiple values are set in separate calls for the same header.
542
543
544       set_header(Headers, {Header, Value})
545              Sets header Header with value Value  in  the  #headers{}  record
546              Headers,  and  returns  a  new #headers{} record. Using the atom
547              undefined for Value effectively  deletes  the  header,  same  as
548              delete_header/2.
549
550
551       set_header(Headers, Header, Value)
552              Same  as  set_header/2  above,  except  Header and Value are not
553              passed in a tuple.
554
555
556       merge_header(Headers, {Header, Value})
557              Merges value Value for header Header with any existing value for
558              that  header in the #headers{} record Headers, and returns a new
559              #headers{} record. Using the atom  undefined  for  Value  simply
560              returns  Headers.  Otherwise,  Value is merged with any existing
561              value already present in the Headers record for  header  Header,
562              comma-separated  from  that  existing  value.  If  no such value
563              exists in  the  Headers  record,  the  effect  is  the  same  as
564              set_header/2.  Note  that  for the Set-Cookie header, values are
565              not comma-separated but  are  instead  collected  into  a  tuple
566              {multi,  ValueList}  where  ValueList  is the collection of Set-
567              Cookie values. This implies that any formatting  fun  passed  to
568              reformat_header/2 must be prepared to handle such tuples.
569
570
571       merge_header(Headers, Header, Value)
572              Same  as  merge_header/2  above, except Header and Value are not
573              passed in a tuple.
574
575
576       get_header(Headers, Header)
577              Gets the value of header Header from the #headers{} record Head‐
578              ers  and returns it. If the header isn't set, the atom undefined
579              is returned.
580
581
582       delete_header(Headers, Header)
583              Deletes any value set for header Header in the #headers{} record
584              Headers, and returns a new #headers{} record.
585
586
587       request_url(ARG)
588              Return  the  url  as  requested by the client. Return value is a
589              #url{} record as defined in yaws_api.hrl
590
591
592
593       parse_url(Str)
594              Parse URL in a string, returns a #url record
595
596
597       format_url(UrlRecord)
598              Takes a #url record a formats the Url as a string
599
600
601       call_cgi(Arg, Scriptfilename)
602              Calls an executable CGI script, given by its full path.  Used to
603              make  `.yaws'  wrappers for CGI programs.  This function usually
604              returns streamcontent.
605
606
607       call_cgi(Arg, Exefilename, Scriptfilename)
608              Like before, but calls Exefilename to handle  the  script.   The
609              file  name  of  the script is handed to the executable via a CGI
610              meta variable.
611
612
613       call_fcgi_responder(Arg)
614              Calls a FastCGI responder.  The address and port of the  FastCGI
615              application  server are taken from the server configuration (see
616              yaws.conf).  Used to make `.yaws' wrappers for  FastCGI  respon‐
617              ders.  Returns the same return values as out/1 (see below).
618
619
620       call_fcgi_responder(Arg, Options)
621              Same  as  above,  but  Options  overrides  the defaults from the
622              server configuration:
623
624
625              Options = [Option]
626              Option -- one of the following:
627
628
629              {app_server_host, string() | ip_address()} The hostname  or  the
630              IP address of the FastCGI application server.
631
632              {app_server_port,  0..65535}  The TCP port number of the FastCGI
633              application server.
634
635              {path_info,   string()}    Override    default    pathinfo    in
636              Arg#arg.pathinfo.
637
638              {extra_env,  ExtraEnv}  Extra environment variables to be passed
639              to the FastCGI application  server,  as  a  list  of  name-value
640              pairs.
641
642
643              ExtraEnv = [Var]
644              Var = {Name, Value}
645              Name = string() | binary()
646              Value = string() | binary()
647
648
649              {trace_protocol, boolean()} Enable or disable tracing of FastCGI
650              protocol messages as info log messages.
651
652              {log_app_error, boolean()} Enable or disable logging of applica‐
653              tion error messages: output to stderr and non-zero exit value.
654
655
656       call_fcgi_authorizer(Arg) -> {allowed, Out} | {denied, Out}
657              Calls a FastCGI authorizer.  The address and port of the FastCGI
658              application server are taken from the server configuration  (see
659              yaws.conf).  Used to make `.yaws' wrappers for FastCGI authoriz‐
660              ers.  Variables contains the values of the variables returned by
661              the  FastCGI application server in the "Variable-XXX: YYY" head‐
662              ers.
663
664              If access is denied, Out contains the complete response returned
665              by  the  FastCGI  application server. This response is typically
666              returned as-is to the HTTP client.
667
668              If access is allowed, Out contains the response returned by  the
669              FastCGI  application  server minus the body (i.e. minus the con‐
670              tent) which should be ignored  per  the  FastCGI  specification.
671              This  response is typically not returned to the HTTP client. The
672              calling application module may wish to inspect the response, for
673              example  by  extracting  variables  (see  fcgi_extract_variables
674              below) or by inspecting the  headers  returned  by  the  FastCGI
675              application server.
676
677
678              Out -- See return values for out/1 below
679
680
681
682       call_fcgi_authorizer(Arg, Options) -> {allowed, Out} | {denied, Out}
683              Same  as  above,  but  Options  overrides  the defaults from the
684              server configuration.  See  call_fcgi_responder/2  above  for  a
685              description of Options.
686
687
688       fcgi_extract_variables(Out) -> [{Name, Value}]
689              Extracts  the  environment  variables  from a FastCGI authorizer
690              response by looking for  headers  of  the  form  "Variable-Name:
691              Value".
692
693
694              Name = string() -- The name of the variable (the "Variable-" prefix
695              has already been removed).
696              Value = string() -- The value of the variable.
697
698
699
700       dir_listing(Arg)
701              Perform  a directory listing. Can be used in special directories
702              when we don't want to  turn  on  dir  listings  for  the  entire
703              server.  Always returns ok.
704
705

RETURN VALUES from out/1

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

AUTHOR

1004       Written by Claes Wikstrom
1005

SEE ALSO

1007       yaws.conf(5) erl(1)
1008
1009
1010
1011
1012                                                                   YAWS_API(5)
Impressum