简体   繁体   中英

Play 2.0 routes file for different configurations

I have a Play 2.0 application with 3 different configurations (application.conf, test.conf and prod.conf)

Now I have a robots.txt file that should be delivered for only test.conf and for the rest environments it should give a 404 if someone tries to access it.

How can I configure my routes file to check if my application is using test.conf? Can I set some variable in test.conf that I can check in the routes file?

Something like this? (pseudo code)

#{if environment = "test"}
GET     /robots.txt                 controllers.Assets.at(path="/public", file="robots.txt")
#{/if}
#{else}
GET     /robots.txt                 controllers.Application.notFoundResult()
#{/else}

You can't add logic in the routes file.

I'd write a controller to serve the robots.txt file. Something like this:

In the routes file:

GET /robots.txt   controllers.Application.robots

Then, in the controller, I'll test if I'm in a testing environment :

def robots = Action {
    if (environment == "test") { // customize with your method
      Redirect(routes.Assets.at("robots.txt"))    
    } else {
      NotFound("")
    }
}

I'm using Scala, but it can be easily translated to Java.

Edit - java sample

You can check if application is in one of three states: prod , dev or test , ie, simple method returning current state:

private static String getCurrentMode() {
    if (play.Play.isTest()) return "test";
    if (play.Play.isDev()) return "dev";
    if (play.Play.isProd()) return "prod";
    return "unknown";
}

you can use as:

play.Logger.debug("Current mode: "+ getCurrentMode()); 

of course in your case that's enough to use these condition directly:

public static Result robots() {
    return (play.Play.isProd())
            ? notFound()
            : ok("User-agent: *\nDisallow: /");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM