[MonkeyScript] [TitleIndex] [WordIndex

* /Stream

An example of a web app script, open rx with a block, mime type handling, a path trick, and how web apps nicely handle streams.

   1 with('io')
   2 with('web.responder')
   3 with('mime.types') {
   4   var mime = new MIMETypes;
   5   File.open('mime.conf', 'rx', function(s) { mime.import(s); }); // x + block; no error is thrown, the block is simply only run if the file exists
   6   function app(env) {
   7     var req = new Request(env);
   8     var res = new Response;
   9     
  10     var path = req.url.path.normalized.relativeTo('/'); // something like /foo/bar/../baz.txt becomes foo/baz.txt perfect for resolving on a FilePath
  11     var f = FilePath.cwd.resolve(path).file;
  12     
  13     if(f.exists) {
  14       if(f.isFile) {
  15         res.header['Content-type'] = mime.typeFor(f.name);
  16         res.body = f.open('rb'); // we pass an open stream to the body, it will automatically be written in a nice streaming way then closed
  17       } else {
  18         res.status = 403;
  19         res.headers['Content-type'] = 'text/plain';
  20         res.body = 'You are not permitted to access this resource.';
  21       }
  22     } else {
  23       res.status = 404;
  24       res.headers['Content-type'] = 'text/plain';
  25       res.body = 'This file does not exist.';
  26     }
  27     return res.finish();
  28   }
  29 }

For reference this can be run with a mod_monkeyscript or a nice quick special FastCGI handler. As well I'll probably write something for file handling up where everything in a public/ directory will be able to be served out when you are using things like the FastCGI rather than things like Apache that handle files on their own.

The normal structure for a web app is:

- /
  |- app.js  - The web app's script
  |- public/ - The public directory of files that may be served out
  `- tmp/    - An optional temp directory

This is respected by mod_monkeyscript and monkeyscript -h fastcgi where in mod_monkeyscript you set the DocumentRoot to the public/ directory and it'll look for an app.js in the parent directory. For monkeyscript -h fastcgi by default it'll look for an app.js in the directory. Both of these can be changed to use something else, for mod_monkeyscript you can set MonkeyScriptApp to a different file name, and monkeyscript -h fastcgi somescript.js can be used in the case of the fastcgi hook.


2010-07-23 04:25