racket / web-server

Other
90 stars 47 forks source link

New wrapping dispatcher for transforming requests and responses #110

Closed jessealama closed 2 years ago

jessealama commented 2 years ago

A common pattern in web development is adding layers of request and response wrapping. That is, a web app often doesn't handle the original incoming request that hit the web server. Rather, it handles an enriched or otherwise transformed request. Similarly, the final response that ultimately gets serialized over the network may not be the response that the app emitted (after any initial request request transformations). As with requests, the final response may be the result of a chain of transformations.

As an example of all this, consider the task of injecting headers. Headers may be added (or changed, or dropped) from a request to store computed values that are needed further down the line. Authentication, for example, or processing cookies fits this pattern.

Another class of examples concerns bodies. Request and response bodies may be similarly intercepted. A response body, for example, might be parsed so that and obscenities or sensitive information can be filtered out. Cookies may be set.

Here we define a new kind of dispatcher that encapsulates this wrapping pattern. Given a servlet (that is, a function from request? to response?), a request transformer (request? . -> . request?) and a response transformer (response? . -> . response?), a dispatcher/c is created that passes the servlet the transformed request, and transforms the response returned by the servlet.

Note that in the documentation there's a reference to version 1.9. That's the same version that introduced the ability to set caching-related headers in the files dispatcher. It seems excessive to me to bump the version again, to 1.10, just for this change. In my view these two changes could be bundled together for the 1.9 release.

jeapostrophe commented 2 years ago

Thanks!