You can import this Gist directly into your LiveBook instance.
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
defmodule MyApp.PostsController do
use Phoenix.Controller, namespace: MyApp
def new(conn, _params) do
conn
|> json(%{hello: "livebook"})
end
end