2016-06-09 52 views
7

我想知道elixir/phoenix框架中的當前網址,我該如何獲取?如何獲取phoenix框架中的當前網址

編輯#1

我的nginx的配置文件:

server { 
     client_max_body_size 100M; 

     listen 80; 

     server_name *.babysittingbordeaux.dev *.babysittingparis.dev 

     access_log /usr/local/var/log/nginx/baby-access.log; 
     error_log /usr/local/var/log/nginx/baby-error.log; 


     location/{ 
      proxy_pass http://127.0.0.1:4000; 
     } 
} 

代碼:

Atom.to_string(conn.scheme) <> "://" <> (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> conn.request_path 

這個例子返回http://127.0.0.1:4000/,我想獲得http://www.babysittingbordeaux.dev/

算我一個 開發模式。

+2

你可以保留原來的標題在nginx的代理服務器。 '''location/{proxy_pass http://127.0.0.1:4000; proxy_set_header主機$主機; }''' –

+0

但我認爲如果你在生產模式下運行,其他方法之一將工作。 –

+0

Dude你是最好的,它的工作!謝謝 –

回答

3

我不確定哪個是最好的方法。

但也許像這樣的內容IndexController內的插圖。

def index(conn, params) do 

    url_with_port = Atom.to_string(conn.scheme) <> "://" <> 
        conn.host <> ":" <> Integer.to_string(conn.port) <> 
        conn.request_path 

    url = Atom.to_string(conn.scheme) <> "://" <> 
      conn.host <> 
      conn.request_path 

    url_phoenix_helper = Tester.Router.Helpers.index_url(conn, :index, params["path"]) # <-- This assumes it is the IndexController which maps to index_url/3 

    url_from_endpoint_config = Atom.to_string(conn.scheme) <> "://" <> 
           Application.get_env(:my_app, MyApp.Endpoint)[:url][:host] <> 
           conn.request_path 

url_from_host_header = Atom.to_string(conn.scheme) <> "://" <> 
         (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> 
         conn.request_path 

    text = ~s""" 

     url_with_port :: #{url_with_port} 

     url :: #{url} 

     url_phoenix_helper :: #{url_phoenix_helper} 

     url_from_endpoint_config :: #{url_from_endpoint_config} 

     url_from_host_header :: #{url_from_host_header} 
    """ 

    text(conn, text) 
    end 
+0

那麼對於主機我得到比「nginx」網址127.0.0.1,是不可能獲得該數據? –

+0

你是在'dev'模式還是'prod'模式下運行你的服務器?我想上面的選項之一應該在'prod'模式下工作? –

+1

如果這些都不起作用,您可以從請求頭獲取主機。 '''Atom.to_string(conn.scheme)<>「://」<> (Enum.into(conn.req_headers,%{})|> Map.get(「host」))<> conn。 request_path'''But我不認爲這是一個很好的方法來做到這一點。使用鳳凰助手可能是在生產模式下運行應用程序的方式。請參閱'config/prod.exs' –

7

如果你只關心你可以使用conn.request_path持有像"https://stackoverflow.com/users/1"值請求路徑。

要獲得包括主機URL,你可以使用

MyApp.Router.Helpers.url(conn) <> conn.request_path 

這將返回象"http://localhost:4000/users/1"結果。

+1

我不想localhost:4000,我想要我在Nginx中配置的域名。合理 ? –

+0

'conn.request_path'只返回沒有查詢字符串的路徑,所以它不是完整的甚至是相對的URL。 –