How to get the current hostname in Heroku

9.3k views Asked by At

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.

3

There are 3 answers

1
Jochen Rau On BEST ANSWER

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.

1
Jeremy On

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.

1
Atty On

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)))))))