๐Ÿ’œ sloanelybutsurely.com
sign in

Single File Phoenix Applications

Sloane ยท

I recently wanted to test how Phoenix handled certain URL params. I needed a way to create a barebones Phoenix app just for the sake of testing a few things out. I knew I could install phoenix and other dependencies for a script using Mix.install/2 but I wasn't sure how to get a minimal Phoenix app running. Some searching turned up this page from Fly's "Phoenix Files" which was great but gave an example using a LiveView. I needed a controller and I wanted to use the Bandit adapter too. So with a few tweaks I ended up with this.

Mix.install(
  [
    {:bandit, "~> 1.6"},
    {:phoenix, "~> 1.7"}
  ],
  config: [
    simple_app: [
      {SimpleApp.Endpoint,
       [
         adapter: Bandit.PhoenixAdapter,
         url: [host: "localhost"],
         http: [ip: {127, 0, 0, 1}, port: 5001],
         server: true,
         secret_key_base: String.duplicate("a", 64)
       ]}
    ]
  ]
)

defmodule SimpleApp.Controller do
  use Phoenix.Controller, namespace: SimpleApp

  def test(conn, _params) do
    # Do whatever testing you want in here!

    send_resp(conn, 200, "ok")
  end
end

defmodule SimpleApp.Router do
  use Phoenix.Router

  pipeline :browser do
    plug(:accepts, ["html"])
  end

  scope "/", SimpleApp do
    pipe_through(:browser)

    get("/", Controller, :test)
  end
end

defmodule SimpleApp.Endpoint do
  use Phoenix.Endpoint, otp_app: :simple_app

  plug(SimpleApp.Router)
end

{:ok, _} = Supervisor.start_link([SimpleApp.Endpoint], strategy: :one_for_one)

Process.sleep(:infinity)