perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.63k stars 1.56k forks source link

Reloading of static assets: Where is "localhost" defined? Documentation clarification .... #1034

Closed mhulse closed 5 years ago

mhulse commented 6 years ago

Hello,

The docs have this example:

if (localhost) {
    String projectDir = System.getProperty("user.dir");
    String staticDir = "/src/main/resources/public";
    staticFiles.externalLocation(projectDir + staticDir);
} else {
    staticFiles.location("/public");
}

But I get:

  symbol:   variable localhost
  location: class Main
/.../Main.java:21: error: illegal start of type
        if (localhost) {
           ^

How do I define localhost? Is that a command line arg that I need to set?

In terms of the docs, and making this issue not a pure question, it might be nice to show or describe how to do this with a more complete example?

mhulse commented 6 years ago

Ok, simple a property fixes the issue:

public static boolean localhost = true;

Any tips on how to flip that for a prod build vs. dev build?

I think where I got thrown off is that the variable name "localhost" implies that there should be something looking for "localhost" in URL ... Which, I'm sure I could engineer ... At first I thought it might be built in to Spark.

mhulse commented 6 years ago

I think someone here suggested:

if (request.host().equals("localhost") || request.host().equals("127.0.0.1")) {
    // local
} else {
    // not
}

Which looks pretty neat in terms of checking if localhost ... Though, where I set staticFiles.location is in the constructor of my Spark app’s main class. I don't see that request is passed in to this class other than when calling/creating routes/before/after/etc.

tipsy commented 6 years ago

Hi @mhulse,

You can launch your app with a dev/localhost config file (using something like args4j), then that could be picked up by an if-statement like the one in your first comment.

Static files have to be configured before starting the server, so there is no way to change the configuration per request.

mhulse commented 6 years ago

@tipsy Thanks!!!!

I'll check out args4j and post back my findings tomorrow (and close out issue). Hopefully this issue will help future noobs. 👍

Appreciate the help!