这就是我一直在寻找的答案。
在应用启动方法中使用 Plug.Router 和 Cowboy:
defmodule HttpServer.Application do
require Logger
use Application
def start(_type, _args) do
children = [
{Plug.Adapters.Cowboy2, scheme: :http, plug: HttpServer.Router, options: [port: 4002]}
]
opts = [strategy: :one_for_one, name: HttpServer.Supervisor]
Supervisor.start_link(children, opts)
end
end
路由器模块如下所示:
defmodule HttpServer.Router do
use Plug.Router
plug(Plug.Logger)
plug(:redirect_index)
plug(:match)
plug(:dispatch)
forward("/static", to: HttpServer.StaticResources)
get "/sse" do
# some other stuff...
conn
end
match _ do
send_resp(conn, 404, "not found")
end
def redirect_index(%Plug.Conn{path_info: path} = conn, _opts) do
case path do
[] ->
%{conn | path_info: ["static", "index.html"]}
["favicon.ico"] ->
%{conn | path_info: ["static", "favicon.ico"]}
_ ->
conn
end
end
end
这里对“/static”的请求被转发到HttpServer.StaticResources模块,但首先,使用plug(:redirect_index)修改“/”和“/favicon.ico”的请求路径。所有静态文件(*.html、*.ico、*.css、*.js 等)都放置在默认位置(project_dir/priv/static)。
最后是 StaticResource 模块:
defmodule HttpServer.StaticResources do
use Plug.Builder
plug(
Plug.Static,
at: "/",
from: :http_server
)
plug(:not_found)
def not_found(conn, _) do
send_resp(conn, 404, "static resource not found")
end
end