Search code examples
elixirwebserver

Elixir httpserver : priv_dir returns something in _build directory, thus I can't send static files that are in source directory


I'm starting Elixir and I'm currently working on a basic web server / API. I'm only using plug_cowboy for now, since I'm focusing on learning the basics.

The server is using plug :match and plug :dispatch to answer to various GET requests. In one of those answers, I'm trying to send HTML files using the send_file function.

My problem being that the server cannot find the files because it doesn't exists where the app searches that file.

HTML file location: lib/httpserver/priv/index.html Searched path: _build/dev/lib/httpserver/priv/index.html

There is the code in the Router:

defmodule Httpserver.Router do
  use Plug.Router

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

  plug :match
  plug :dispatch

  get "/" do
    priv_dir = :code.priv_dir(:httpserver)
    index_path = Path.join([priv_dir, "index.html"])
    send_file(conn, 200, index_path)
  end

  get "/:name" do
    send_resp(conn, 200, "Welcome, #{name} !")
  end

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

I have tried:

  • looking at ERLang's documentation
  • looking at various elixir forum posts
  • looking at some older stack overflow posts

All I could find was about the start_permanent and build_embedded options in mix.exs's project function, and did not solver my problem.


Solution

  • :code.priv_dir/1 is a helper which knows nothing about your actual code, it just grabs the path where the application runs and concatenates it with "priv". After all, in production one does not even have a source folder.

    You should either copy the folder manually or use File.cwd/0 instead.