Skip to content

Instantly share code, notes, and snippets.

@teamon
Last active January 19, 2022 01:23
Show Gist options
  • Save teamon/a964dd80bc5c6802e3a8548efdda9cff to your computer and use it in GitHub Desktop.
Save teamon/a964dd80bc5c6802e3a8548efdda9cff to your computer and use it in GitHub Desktop.
Run Phoenix inside LiveBook

Phoenix in LiveBook

Info

You can import this Gist directly into your LiveBook instance.

Setup

Mix.install([:jason, :plug_cowboy, :phoenix, :phoenix_html, :phoenix_live_view])
Application.put_env(:phoenix, :json_library, Jason)
Application.put_env(:myapp, MyApp.Endpoint, server: true, http: [port: 8081])
defmodule MyApp.Router do
  use Phoenix.Router

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

  scope "/", MyApp do
    pipe_through([:browser])
    get("/", PostsController, :new)
  end
end
defmodule MyApp.Endpoint do
  use Phoenix.Endpoint, otp_app: :myapp

  @session_options [
    store: :cookie,
    key: "_myapp_key",
    signing_salt: "LK05NtfN"
  ]

  socket("/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]])

  plug(Plug.Static,
    at: "/",
    from: :myapp,
    gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)
  )

  plug(Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library()
  )

  plug(Plug.MethodOverride)
  plug(Plug.Head)
  plug(Plug.Session, @session_options)
  plug(MyApp.Router)
end
case MyApp.Endpoint.start_link() do
  {:ok, _pid} ->
    :ok

  {:error, {:already_started, pid}} ->
    true = Process.exit(pid, :normal)
    {:ok, _} = MyApp.Endpoint.start_link()
end

App

defmodule MyApp.PostsController do
  use Phoenix.Controller, namespace: MyApp

  def new(conn, _params) do
    conn
    |> json(%{hello: "livebook"})
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment