Building42 / Telegraph

Secure Web Server for iOS, tvOS and macOS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add middleware to specific routes

Joebayld opened this issue · comments

Hey all,

Love this library - just getting used to it. I'm curious if it's possible to apply a middleware to a certain set of routes? I only want to add some header middleware to a specific set of URIs but it seems that middleware applies to all routes currently.

Any ideas?

Hi, great to hear you love the library! That's awesome!

It isn't possible right now to apply middleware to a specific route. The solution right now would be to check the request URI in your middleware and then choose to just call the next handler if the middleware doesn't apply to this route. This reduces the reusability of the middleware a bit, but worst case you can create a middleware class and then have a route-specific middleware class extend from it.

It would be great if we could have middleware support on a route level. Looking at the code, I think this could be the way to do that:

  1. add code to HTTPRoute for it to store an array of request handlers (see requestHandlers and requestChain in HTTPConfig). You could even store a HTTPConfig per route, that would be more work though.
  2. add code to HTTPRouteHandler to call the route's requestChain. This could probably be as easy as changing the return try route.handler(request) call on line 41
  3. add code to Server+Routing.swift, you'll need a few helpers there to specify the handlers when you create a route. Although you could just use route(_ httpRoute: HTTPRoute).

Unfortunately I'm a bit short on time these days to implement a lot of this myself, but I'd be happy to help out whenever I have some time.