12

I'm playing around with deploying Clojure/Noir apps on Heroku and I've got my app mostly working. However, one final piece I need is to figure out the hostname of my app when deployed on Heroku. Ideally, I want to do this dynamically instead of hard-coding it.

So, if for example, my app's URL is 'http://freez-windy-1800.herokuapp.com', I want to be able to dynamically get this within my clojure code.

I know that I can look at the incoming request to figure this out, but ideally, I'd like to have some sort of 'setting' where I evaluate an expression once and save the value in a variable that I can then use (coming from the Python/Django world, I'm thinking of the settings.py equivalent in Clojure).

For reference, the code I'm deploying is available at https://github.com/rmanocha/cl-short.

animuson
  • 53,861
  • 28
  • 137
  • 147
Rishabh Manocha
  • 2,955
  • 3
  • 18
  • 16

3 Answers3

7

You could set an environment variable in Heroku by

heroku config:add BASE_IRI=http://freez-windy-1800.herokuapp.com

and read it back in Clojure

(defn- base-iri []
  (or (System/getenv "BASE_IRI") "http://localhost/"))

Heroku already sets the PORT you can use

(defn -main []
  (let [port (Integer. (or (System/getenv "PORT") 8080))]
    (run-jetty #'app {:port port})))

Works for me in different environments.

Jochen Rau
  • 390
  • 1
  • 6
3

You would typically do this with InetAddress from the Java standard library.

(.getCanonicalHostName (java.net.InetAddress/getLocalHost))

This, however, does not do a DNS lookup.

Jeremy
  • 22,188
  • 4
  • 68
  • 81
  • 1
    This doesn't seem to work. On Heroku (using `heroku run lein repl`) I get some random numbers. On localhost, I get my local IP. – Rishabh Manocha May 21 '12 at 14:32
-1

3 ways to get the hostname. Use as you wish.

(ns service.get-host-name
  (require [clojure.java.shell :as shell]
           [clojure.string :as str])
  (:import [java.net InetAddress]))

(defn- hostname []
  (try
    (-> (shell/sh "hostname") (:out) (str/trim))
    (catch Exception _e
      (try
        (str/trim (slurp "/etc/hostname"))
        (catch Exception _e
          (try
            (.getHostName (InetAddress/getLocalHost))
            (catch Exception _e
              nil)))))))
Atty
  • 691
  • 13
  • 20