| 1 | Middleware is feature The idea of the Helma NG webapp framework that provides a simple interface middleware is to inject additional code between wrap the web server and [JSGI] application (or any middleware already wrapping the web applicationapplication) to run some pre- or post-request code. Middleware uses Since middleware exposes the same calling conventions as web app actions: a function that takes a Request object as argument and returns a Response objectJSGI interface to the outside world, it can be nested or "stacked" at will. |
| 3 | Since Usually, JSGI middleware wraps the web comes as a function that takes a JSGI application (and any middlware stacked upon it)as argument, it is in full control of how the request is processedand returns a middleware function wrapping that app. For example, a simple middleware that adds logging to each request might be implemented as follows: |
| 5 | * Inspect and modify the request object before processing it further exports.Logger = function(app) |
| 6 | * Decide not to pass the request on, returning its own response instead return function(env) |
| 7 | * Inspect and modify the response obtained from the application log(env.SCRIPT_NAME + env.PATH_INFO); |
| 8 | return app(env); |
| 9 | }; |
| 10 | } |
| 11 | |
| 12 | The middleware that comes with Helma NG follows this pattern. Additionally, the Helma NG JSGI implementation offers a convenience feature to automatically instantiate and wrap middleware so you don't have to. All you need to do is export your middleware factory functions as an array called `middleware` in your `config` module. If your middleware factory function is called `middleware` or `handleRequest` it is even enough to just export the module name: |
| 7 | Middleware is configured in an exported Array called <code>middleware</code> in the app's <code>config</code> module. By convention, the webapp looks for a function called <code>handleRequest</code> in middleware modules exports.middleware = |
| 8 | 'helma/middleware/gzip', |
| 9 | 'helma/middleware/etag', |
| 10 | 'helma/middleware/error', |
| 11 | 'helma/middleware/notfound' |
| 12 | ]; |
| 9 | The <code>request</code> argument contains a <code>process</code> method that is used to pass above list shows some of the request on in the middleware chainthat comes with Helma NG. Thus, Have a middleware implementation that just passes on the request might look like this:at the [modules/helma/middlware][http://github.com/hns/helma-ng/tree/master/modules/helma/middleware] directory for more middleware. |
| 11 | Of course, the great thing about JSGI middleware is that it's easy to write your own, exportsor use middleware from another package. |
| 12 | return req.process(); |
| 13 | } |
| 14 | |
| 15 | Have a look at the *modules/helma/middlware|http://github.com/hns/helma-ng/tree/master/modules/helma/middleware* directory for the standard middleware currently shipping with Helma NG. |