A directive that can be used at the top most level of my routes that enables CORS support for all the routes contained on it. That means:
- Respond to OPTIONS requests with the right headers only for the registered paths (that is, OPTIONS /something-that-does-not-exist should result in a 404, not a 405
- Add the Access-Control-Allow-Origin header to every request
After some digging, I found out that spray has very good support for something like this.
For the first part, responding to OPTIONS, it is as easy as looking at the response, see if it is going to be rejected and, if the cause of the rejection is 'MethodNotSupported' that means that there is a route somewhere inside your CORS directive that would respond to this uri with a different method. That is, if the request was an options, we have to respond OK as it is a preflight request. We can even build the list of allowed methods for Access-Control-Allow-Methods from the list of rejections.
For the second part, all we need to do is to add the header to the response.
You can find the code here: https://gist.github.com/joseraya/176821d856b43b1cfe19