Serve files from priv/web
folder and sub folders.
use Plug.Router
plug :match
plug :dispatch
match "/*glob" do
case glob do
[] ->
path("index.html") # or whatever your index file is
|> send_file(conn)
_ ->
path(Path.join(glob))
|> send_file(conn)
end
end
def path(parts) do
if Mix.env != :dev do
Path.join(:code.priv_dir(:my_application), "web") |> Path.join(parts)
else
# Assume current working directory is mix project folder
Path.join("priv/web", parts)
end
end
def send_file(path, conn) when (is_binary(path)) do
case not File.dir?(path) and File.exists?(path) do
true ->
conn
|> put_resp_header("content-type", MIME.from_path(path))
|> send_file(200, path)
false -> send_resp(conn, 404, "Not found")
end
end
Parse all sorts of parameters. Need Poison library for parsing JSON. Check conn.params
for parsed result, e.g. if the key is "filename" then conn.params["filename"]
.
plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json],
pass: ["text/*"],
json_decoder: Poison
post "user/get/*user_id" do
rs = with [user_id] <- conn.params["user_id"], # from url
fields <- conn.params["fields"], # from json post body
true <- not is_nil(user_id),
rep <- (fn ->
IO.puts "GET user #{user_id}"
case get_user(user_id, fields) do
{:ok, u} -> %{"result": u}
{:error, reason} -> %{"error": reason}
end
end).(),
do: {:ok, rep}
case rs do
{:ok, rep} ->
send_resp(conn, 200, Poison.encode!(rep))
_ ->
send_resp(conn, 400, "Bad request")
end
end