STeve Shary
STeve Shary

Reputation: 1505

How to set ring port based on profile

I have a clojure ring project and I want to be able to set the port number based on the profile. Currently I have the following snippet from project.clj

:plugins [[lein-ring "0.8.13"]]
:ring {:handler project.handler/webServer
       :init    project.init/initialize
       :port    80}
:profiles {:dev        {:jvm-opts ["-Dproperty-file=dev.properties"]}
           :ci         {:jvm-opts ["-Dproperty-file=ci.properties"]}
           :uberjar    {:aot :all}})

What I would like to do is to set the port to 8080 for development environments and then port 80 for the production environment. I would run on port 80 all the time but that requires root privilege and not something I want to do for a dev run. I have tried (blindly) to put the ring port into the uberjar profile but that didn't work. I also tried to use the environ project to set the ring port based on the environment variable but that didn't work either.

I am open to a solution that passes command line arguments to the java -jar [...]-standalone.jar command but I am stuck on how to get any approach to work.

Upvotes: 4

Views: 937

Answers (2)

user3570037
user3570037

Reputation: 1

It seems the alternative version doesn't work as stated. I get the exception "java.lang.String cannot be cast to java.lang.Number". Apparently we have to explicitly parse the value environment variable as integer, but then we also have to catch possible errors. Code that works for me

:port ~(try
              (Integer/valueOf
                (System/getenv "RING_PORT"))
              (catch Exception e 3000))

Upvotes: 0

sbensu
sbensu

Reputation: 1521

You don't need environ. Use it when you need to access configuration variables in the source code. In project.clj you could directly do this:

:profiles {:dev        {:jvm-opts ["-Dproperty-file=dev.properties"]
                        :ring {:port 8080}}
           :ci         {:jvm-opts ["-Dproperty-file=ci.properties"]
                        :ring {:port 80}}
           :uberjar    {:aot :all
                        :ring {:port 80}}})

I have tested this (without jvm-opts and port 8081 instead of 80) and it works.

Alternative: if they are different machines, you could use the OS's environment variables:

:ring {:handler project.handler/webServer
       :init    project.init/initialize
       :port    ~(System/getenv "RING_PORT")}

And then set RING_PORT to 8080 in your dev machine and 80 on the production machine.

$ export RING_PORT=80

Upvotes: 5

Related Questions