julienschmidt / httprouter

A high performance HTTP request router that scales well
https://pkg.go.dev/github.com/julienschmidt/httprouter
BSD 3-Clause "New" or "Revised" License
16.57k stars 1.47k forks source link

Ability to register handlers as observer for specific params #143

Open h2non opened 8 years ago

h2non commented 8 years ago

In order to simplify logic and avoid code duplication while running redundant tasks for certain path params, it would be great adding some sort of path param specific handlers who observes if a given dynamic param is present in the matched router, and then trigger those handlers to perform custom tasks, such as validations, DB queries...

A representative example could be:

router := httprouter.New()
// Register a route as usual
router.Get("/users/:name/:action", handler)
// We want to perform some task every time the :arg param is present in any matched router
router.Param("name", validateUser, loadSession)

The router execution order should be:

1) Match incoming request against the radix tree (as it is today)
2) Extract path dynamic params
3) Trigger path param specific handlers (if they're present)
4) Trigger final router handler.
rickb777 commented 8 years ago

This seems like it might add a lot of extra complexity for not a lot of benefit. If your params have a finite set of possible values, you could just register the routes explicitly. Perhaps you could provided a stronger justification for your idea.

julienschmidt commented 7 years ago

@h2non any answer to @rickb777's comment?