Current section
Files
Jump to
Current section
Files
lib/mflask/middleware/static.ex
defmodule Mflask.Middleware.Static do
@moduledoc """
Static file serving middleware.
## Usage
use Mflask
plug Mflask.Middleware.Static, at: "/static", from: "priv/static"
## Options
- `:at` — URL prefix to serve under (default: `"/static"`)
- `:from` — filesystem path to serve files from (default: `"priv/static"`)
## Example
A request to `/static/app.css` will serve `priv/static/app.css`.
"""
@behaviour Plug
@impl true
def init(opts) do
%{
at: Keyword.get(opts, :at, "/static"),
from: Keyword.get(opts, :from, "priv/static")
}
end
@impl true
def call(conn, %{at: at, from: from}) do
prefix = String.trim_leading(at, "/")
case conn.path_info do
[^prefix | rest] ->
rel_path = Path.join(rest)
abs_path = Path.join([from, rel_path])
if File.exists?(abs_path) and not File.dir?(abs_path) do
mime = MIME.from_path(abs_path)
conn
|> Plug.Conn.put_resp_content_type(mime)
|> Plug.Conn.send_file(200, abs_path)
|> Plug.Conn.halt()
else
conn
end
_ ->
conn
end
end
end