I have many controllers in my play 2.4.x application.
I want to get a list of all route URLs
pointing their respective controllers. I know how to get the URL from the current request. But I need a list of all the URLs available inside a play application.I want to generate this list dynamically because URLs can be changed/added/deleted in future
.
So,is there some way I can generate this URL list dynamically ? Or do I have the obligation to store all the URLs statically somewhere in cache or dictionary ?
The conf/routes file is the configuration file used by the Router. This file lists all the routes needed by the application.
The router is the component in charge of translating incoming HTTP Requests into action calls (a static, public method of a Controller).
The routes file syntax conf/routes is the configuration file used by the router. This file lists all of the routes needed by the application. Each route consists of an HTTP method and URI pattern, both associated with a call to an Action generator.
I obtained the desired list by using the documentation
method provided by Router trait. The documentation method returns Seq[(String, String, String)]
.Here each tuple has the format:
( {http-method} , {url} , {controller method} )
The Router trait is extended by all the autogenerated Routes.scala
classes. Scala-compiler generated a separate Routes.scala
for each routes
file in the application. These auto-generated Routes.scala
files implement all the methods of Router trait including the documentation method that we discussed above.
So,to get list of all URLs, I simply had to inject the Router trait
and then access the documentation method
:
import play.api.routing.Router
class MyClass @Inject()(router: Router) {
def getAllURLs:Seq[String] = router.documentation.map(k => k._2)
}
Update for Play 2.7, Scala:
class MyController @Inject()(routesProvider: Provider[play.api.routing.Router]) {
lazy val routes: Seq[(String, String, String)] = routesProvider.get.documentation
}
from discussion for play 2.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With