Skip to content

Instantly share code, notes, and snippets.

@tiagoefmoraes
Forked from teamon/phoenix.md
Last active December 16, 2021 01:13
Show Gist options
  • Save tiagoefmoraes/f99c7ef8eed6d9d8625dc29a9d506ba1 to your computer and use it in GitHub Desktop.
Save tiagoefmoraes/f99c7ef8eed6d9d8625dc29a9d506ba1 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)
    ref = Process.monitor(pid)
    receive do
      {:DOWN, ^ref, _, _, _} ->
        {:ok, _} = MidSmtp.Endpoint.start_link()
    end    
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