Custom dynamic routing logic

Hi, I have the following business case - to implement custom dynamic routing. The routing logic will still be based on url path, let's say it's a function f(path). f(path) is not trivial so I want to implement it as a middleware. The problem is that the output of f(path) should affect the further routing, and here's when I need some help. Basically, I have one idea how to achieve this:
To have a common entry routing rule with this MW. Inside MW to set a header to my request and forward it to traefik again via loopback interface. This way I could apply different set of routing rules based on that header;
But it still feels to me a bit dirty and I want to know whether is a more elegant way to solve this.

In Traefik routing is done by the router, middleware is invoked after, it’s always the same target service for a router.

So your idea probably does not work with Traefik.

The idea is that one of the services is traefik itself