Skip to content

Instantly share code, notes, and snippets.

@NicolaeNMV
Last active August 29, 2015 14:06
Show Gist options
  • Save NicolaeNMV/3d375ca2e4b43aa6014f to your computer and use it in GitHub Desktop.
Save NicolaeNMV/3d375ca2e4b43aa6014f to your computer and use it in GitHub Desktop.
Check dynamically if a route path exists in play2 framework
/*
routes:
GET /test controllers.Application.test(route: String)
GET /guessThat controllers.Application.guessIt
// To check:
/test?route=/guessIt
Will yield "It exists!"
*/
object PlayUtils {
import play.api.Play.current
/**
* Check if a route exists or not
* @param requestSample - used to construct a new request with @param method and @param path
*/
def routeExists(requestSample: Request[_], method: String, path: String): Boolean = {
val requestToTest = requestSample.copy(method = method, path = path)
Play.routes
.flatMap(_.handlerFor( requestToTest ))
.map(_ => true)
.getOrElse(false)
}
}
object Application extends Controller {
def index = Action {
Ok("Index")
}
def test(route: String) = Action { request =>
if (PlayUtils.routeExists(request, "GET", route)) {
Ok("It exists !")
} else {
NotFound("Route not found")
}
}
def guessIt = Action {
Ok("test")
}
}
@domdorn
Copy link

domdorn commented Sep 14, 2014

shouldn't
/test?route=/guessIt
yield
"Route not found" ?
After all, its mapped to guessThat
GET /guessThat controllers.Application.guessIt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment