Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: per-endpoint middleware #188

Closed
hasryan opened this issue Apr 28, 2016 · 5 comments
Closed

Question: per-endpoint middleware #188

hasryan opened this issue Apr 28, 2016 · 5 comments

Comments

@hasryan
Copy link

hasryan commented Apr 28, 2016

I have a question that is similar to #175 but I'm not sure it's exactly the same use case and would appreciate an opinion on my example below.

I am building an API and have some endpoints that require different middleware. The problem is that many of these endpoints are siblings, or have the same path but use a different verb, and are generally organized in ways that I can't apply the same middleware to a common prefix such as /admin/*.

For example, I need one series of middleware to be applied for requests to POST /foo/bar and another, different collection of middleware to be applied for GET /foo/bar. And yet another, distinct collection of middleware applies for DELETE /foo. I basically need the flexibility to apply a unique set of middleware to any given method+pattern combination.

The following appears to work, but it's not intuitive to me (providing sub-Muxes to the root Mux as if they were Handler functions, since *Mux implements that interface) and I would like to know if this is considered a reasonable way to solve my problem or if it's a hack. If this isn't a reasonable way to solve it, is there another method I can use to achieve my goal?

getFooBarMux := web.New()
getFooBarMux.Use(getFooBarMiddleware)
getFooBarMux.Get("/foo/bar", getFooBarHandler)

postFooBarMux := web.New()
postFooBarMux.Use(postFooBarMiddleware)
postfooBarMux.Post(postFooBarHandler)

deleteFooMux := web.New()
deleteFooMux.Use(deleteFooMiddleware)
deleteFooMux.Delete(deleteFooHandler)

rootMux := web.New()
rootMux.Get("/foo/bar", getFooBarMux)
rootMux.Post("/foo/bar", postFooBarMux)
rootMux.Delete("/foo", deleteFooMux)
@hasryan
Copy link
Author

hasryan commented Apr 28, 2016

To be clear, most of my handlers use similar middleware, but there are a few exceptions and that is why I am trying to achieve this level of flexibility.

@zenazn
Copy link
Owner

zenazn commented Apr 28, 2016

Would it be appropriate to inline the functionality in these specific middlewares into your handlers directly? It's hard to know for sure if that would result in an unacceptable amount of duplication, but depending on your use case it might be just as verbose as whatever solution you come up with using middleware.

Alternatively, it's pretty easy to write "inline" middleware stacks. I know several libraries that provide just this, which you might find useful. Alternatively, you can wrap the behavior you're already using above with Goji into a reusable helper to make your life a bit easier.

Finally, some middleware can easily determine (by looking at the URL or similar) if they should run on any given request. In this case, you can include each of these custom middleware in the global middleware stack, with the understanding that each layer knows when it should or should not run.

@hasryan
Copy link
Author

hasryan commented Apr 28, 2016

@zenazn thank you for your response.

Would it be appropriate to inline the functionality in these specific middlewares into your handlers directly? It's hard to know for sure if that would result in an unacceptable amount of duplication, but depending on your use case it might be just as verbose as whatever solution you come up with using middleware.

Originally I did have the handler-specific functionality in each handler definition but it became unwieldy and I saw a lot of duplication. Also, the functionality in the middleware feels most appropriate to apply prior to invoking the handler. For instance, a few of my handlers support HTTP Basic Auth while the majority only support a custom authentication protocol.

The above example is somewhat contrived -- in reality I have about 8 common middleware that every handler uses, but a few of them have an additional handful of middleware that get added in addition to the common ones. And a few do not use the common stack of middleware at all.

Alternatively, it's pretty easy to write "inline" middleware stacks. I know several libraries that provide just this, which you might find useful.

Can you direct me to one of these so I can see how it works?


Could you also comment on whether the approach I'm taking my example is technically valid or if I've overlooked some issue? I've traced through the codebase and I don't see any issues but perhaps I'm missing something. I couldn't find any examples in the wild that are using 1 mux per route, and that makes me a little uncomfortable with this pattern.

Part of the reason I arrived at the above example is because I define all my handlers in a single slice, with each element in the slice being a struct that defines the verb, pattern, handler function, and a slice of middleware to apply. I find this method of defining my routes is aesthetically pleasing and is more condensed than using subrouters or putting conditional logic in a common set of middleware. For example:

endpoints := []endpoint{
  {
    verb: "POST",
    pattern: "/foo/bar",
    middlewares: append(commonMiddlwares, postFooBarMiddleware),
    handler: PostFooBarHandler,
  },
  {
    verb: "GET",
    pattern: "/foo/bar",
    middlewares: append(commonMiddlwares, getFooBarMiddleware),
    handler: GetFooBarHandler,
  },
  {
    verb: "DELETE",
    pattern: "/foo",
    middlewares: append(commonMiddlwares, deleteFooMiddleware),
    handler: DeleteFooHandler,
  },
}

mainMux := web.New()

for _, endpointConfig := range endpoints {  
  endpointMux := web.New()
  for _, endpointMiddleware := endpointConfigs.middlewares {
    endpointMux.Use(endpointMiddleware)
  }

  switch endpoint.verb {
  case "GET":
    endpointMux.Get(endpointConfig.pattern, endpointConfig.handler)
    mainMux.Get(endpointConfig.pattern, endpointMux)
  case "POST":
    endpointMux.Post(endpointConfig.pattern, endpointConfig.handler)
    mainMux.Post(endpointConfig.pattern, endpointMux)
  case "DELETE":
    endpointMux.Delete(endpointConfig.pattern, endpointConfig.handler)
    mainMux.Delete(endpointConfig.pattern, endpointMux)
  }
}

@zenazn
Copy link
Owner

zenazn commented May 7, 2016

Can you direct me to one of these so I can see how it works?

One that comes to mind is https://github.com/justinas/alice (although it is net/http-only), but you can also extract Goji's own middleware stack implementation into a standalone library if you like.

As for your code snippet at the bottom, it looks totally reasonable. It is a little unusual to use so many muxes, but given that the entire system is explicitly designed with composability in mind I see no reason why it shouldn't work well for you.

@hasryan
Copy link
Author

hasryan commented May 9, 2016

Thank you, this is very helpful!

@hasryan hasryan closed this as completed May 9, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants