Elixir plug, '/' -> static/index.html

  1. No, I am not using Phoenix. I am using cowboy, plug, plug_cowboy.

  2. I have a basically working setup with:

defmodule ExServer.Static do
  use Plug.Builder

  plug Plug.Static,
    at: "",
    from: :ex_server

  plug :not_found

  def not_found(conn, _) do
    send_resp(conn, 404, "static not found")
  end

end


defmodule ExServer.Router do

  use Plug.Router
  use Plug.Debugger
  require Logger

  forward("/static", to: ExServer.Static)


  plug(Plug.Logger, log: :debug)
  plug(:match)
  plug(:dispatch)


  get "/" do

  end


  get "/hello" do
    send_resp(conn, 200, "world")
  end


  match _ do
    send_resp(conn, 404, "not found")
  end

end

The part that is missing: I want “/” to end up loading “static/index.html” (which amps to “priv/static/index.html” on the file system). How can I do this?

Use Plug.Conn.send_file/5 for that.

So whole code will look like:

priv_dir = :code.priv_dir(:ex_server)
index_path = Path.join([priv_dir, "static", "index.html"])

send_file(conn, 200, index_path)
2 Likes