Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current base domain of a Phoenix app?

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.

like image 237
Meji Avatar asked Oct 25 '16 14:10

Meji


3 Answers

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

like image 70
TheAnh Avatar answered Oct 21 '22 09:10

TheAnh


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.

like image 30
Sheharyar Avatar answered Oct 21 '22 11:10

Sheharyar


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"
like image 32
Alexandr Sysoev Avatar answered Oct 21 '22 11:10

Alexandr Sysoev