我不会推荐它(我会推荐有两个控制器并将你的逻辑移动到两个控制器调用的不同模块中),但它可以完成。您可以共享一个控制器,但您仍然需要一个单独的管道来确保设置正确的响应类型(html/json)。
以下将使用相同的控制器和视图,但根据路由呈现 json 或 html。 “/”是html,“/api”是json。
路由器:
defmodule ScopeExample.Router do
use ScopeExample.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", ScopeExample do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
scope "/api", ScopeExample do
pipe_through :api # Use the default browser stack
get "/", PageController, :index
end
end
控制器:
defmodule ScopeExample.PageController do
use ScopeExample.Web, :controller
plug :action
def index(conn, params) do
render conn, :index
end
end
查看:
defmodule ScopeExample.PageView do
use ScopeExample.Web, :view
def render("index.json", _opts) do
%{foo: "bar"}
end
end
如果您使用以下路由器,您还可以共享路由器并通过同一路由为所有内容提供服务:
defmodule ScopeExample.Router do
use ScopeExample.Web, :router
pipeline :browser do
plug :accepts, ["html", "json"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end
scope "/", ScopeExample do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
end
然后,您可以在网址末尾使用 ?format=json 指定格式 - 不过,我建议您为 API 和网站使用不同的网址。