What's the idiomatic way to get a base domain for a Phoenix/Elixir app? Not of a single request, but a a base domain of an application, which probably depends on its current environment.
So locally it's should be localhost
, but on a server, it can be "dev.my_domain.com", "my_domain.com" or something else that I can use in my Application.
I can, of course, add a special key in a config/dev.exs
or config/prod.exs
, but I thought that there might already be such a key somewhere which I can reuse.
You are looking for the host
.It's a request field stored in Plug.Conn
struct.
host - the requested host as a binary, example: "www.example.com"
Request Fields
For requests, you should use the host
field in the Plug.Conn
like @TheAnhLe suggested.
But if you're looking to get the domain otherwise, Phoenix lets you specify the url
parameter in your application Endpoint
config:
# config/prod.exs
config :my_app, MyAppWeb.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com", port: 80],
# more configs...
You can use these methods to get the host's value:
MyAppWeb.Endpoint.url()
# => "http://localhost:4000"
MyAppWeb.Endpoint.host()
# => "localhost"
This value defaults to localhost
when not specified.
Update: For Phoenix versions prior to 1.3, replace MyAppWeb
with MyApp
.
With phoenix 1.3.0 (don't know about older versions) you can call url/0
from Endpoint API
For example:
iex(1)> TestWeb.Endpoint.url
"http://localhost:4000"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With