如何设置子域以服务于所有API流量?

发布于 2025-02-04 02:38:51 字数 194 浏览 4 评论 0 原文

我在 example.com 上的一个实例上运行了一个Web应用程序。它在 xpemens.com/api 上具有API。

我想设置一个子域 api.example.com ,并为该子域的所有API流量提供服务。

在单个实例中运行时,如何为子域中的所有API流量服务?

I have a single web app running on a single instance on example.com. It has an API at example.com/api.

I want to set up a subdomain api.example.com and serve all API traffic from that subdomain.

How do I serve all API traffic from the subdomain while running off a single instance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回首观望 2025-02-11 02:38:51

您可以在路由器级别进行设置。看看这个例子

简而言之。

  • 定义 apirouter 它具有所有与API相关的路由。
  • 将插件插入app endpoint 直接在主路由器之前,以处理 apirouter 的请求。
# endpoint.ex
plug YourApp.Plug.Subdomain, YourApp.APIRouter
plug YourApp.Router

插头的逻辑应该是:

defmodule YourApp.Plug.Subdomain do
  import Plug.Conn

  @doc false
  def init(default), do: default

  @doc false
  def call(conn, router) do
    case get_subdomain(conn.host) do
      subdomain when subdomain == "api" ->
        # If it is from API -> initialize/match current request to APIRouter
        conn
        |> router.call(router.init({}))
        |> halt()

      _ -> conn # If it's not -> continue with current AppRouter
    end
  end
  
  # A function to get current subdomain or try to match it, your call.
  defp get_subdomain(host) do
    root_host = Subdomainer.Endpoint.config(:url)[:host]
    String.replace(host, ~r/.?#{root_host}/, "")
  end
end

You can set it up at router level. Take a look at this example
https://blog.gazler.com/blog/2015/07/18/subdomains-with-phoenix/

In short.

  • Define an APIRouter where it has all API related routes.
  • Put a plug at app endpoint right before the main router to handle requests to the APIRouter.
# endpoint.ex
plug YourApp.Plug.Subdomain, YourApp.APIRouter
plug YourApp.Router

The logic for the plug should be:

defmodule YourApp.Plug.Subdomain do
  import Plug.Conn

  @doc false
  def init(default), do: default

  @doc false
  def call(conn, router) do
    case get_subdomain(conn.host) do
      subdomain when subdomain == "api" ->
        # If it is from API -> initialize/match current request to APIRouter
        conn
        |> router.call(router.init({}))
        |> halt()

      _ -> conn # If it's not -> continue with current AppRouter
    end
  end
  
  # A function to get current subdomain or try to match it, your call.
  defp get_subdomain(host) do
    root_host = Subdomainer.Endpoint.config(:url)[:host]
    String.replace(host, ~r/.?#{root_host}/, "")
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文