LiveBook is a new application launched by the elixir team, which can be used to easily write articles in the browser and run elixir code in it.
I'm curious if we can use LiveBook to directly change the routing configuration of the current server, allowing us to deploy the service in real time. For example, we write a page in LiveBook, and then configure it directly to a certain url path, and others can access it. This feels very cool, saves the cumbersome configuration packaging and publishing process, and is completely achievable in theory.
Just do it. First of all, I deployed a free livebook instance on fly.io. You can also deploy it locally, which is very convenient.
After startup, select Runtime settings
in the configuration button on the left, and Embedded
. That is, the code is executed in the erlang node of the livebook itself. In order to ensure security and isolation, the livebook will start another node to execute the code by default, that is, the Elixir standalone
option, but we cannot modify the routing configuration.
After making the changes, I created a new document and started writing code. Livebook uses the Phoenix framework, the underlying HTTP server is Cowboy, and then the bottom layer is ranch. So we first get some information about the current server through :ranch.info()
. From the return value, we know that the ref of the current ranch server is LivebookWeb.Endpoint.HTTP
, and all the routing (or distribution Dispatch) configurations are saved here. The next step is to modify the dispatch configuration.
Each http request will be dispatched to a different handler (how to translate this, grab?), so we first need to write a handler for testing.
defmodule TestHandler do
@behaviour :cowboy_handler
def init(req, state) do
req = :cowboy_req.reply(200, %{
"content-type" => "text/plain"
}, "Hello World!", req)
{:ok, req, state}
end
end
Its functionality is very simple, returning to the hello world no matter what it receives. Next, configure it into our dispatch, pay attention to keep the previous dispatch content, otherwise our livebook will not be accessible haha.
dispatch = :cowboy_router.compile([{:_, [], [
{'/test', [], TestHandler, %{}},
{:_, [], Phoenix.Endpoint.Cowboy2Handler, {LivebookWeb.Endpoint, []}}
]}])
Finally, use the real-time update function provided by cowboy to deploy the new configuration to our ranch server:
:cowboy.set_env(LivebookWeb.Endpoint.HTTP, :dispatch, dispatch)
Try to access the path we configured. It worked!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。