How to get the current hostname in Heroku
Asked Answered
C

3

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.

Cary answered 21/5, 2012 at 13:50 Comment(0)
O
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.

Off answered 22/5, 2012 at 10:36 Comment(1)
I just saw that you already do the PORT part. So, it should work for you, too.Off
R
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.

Rijeka answered 21/5, 2012 at 14:4 Comment(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.Cary
H
-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)))))))
Hecht answered 21/9, 2018 at 9:4 Comment(1)
worst readability I know to date ,what language is this ? .. ou famous Clojure :)Cheryle

© 2022 - 2024 — McMap. All rights reserved.