接續前一篇的 application
現在要讓 application 啟動的時候,也開啟網頁伺服器
目前 Elixir 有兩個常用的網頁伺服器 (web server) 套件可以選擇
在這邊我們安裝並使用 bandit
mix.exs
的 deps
函式加上 bandit defp deps do
[
{:bandit, "~> 1.8"}
]
end
加上這行後可以執行 mix deps.get
讓他下載套件
接著我們把 Bandit 填入 application start 時要啟動並監督的 children 裡
defmodule MySite do
use Application
def start(_type, _args) do
children = [Bandit]
IO.puts("Starting Server")
opts = [strategy: :one_for_one]
Supervisor.start_link(children, opts)
end
end
但在我們啟動我們的服務時出現一個 runtime error
(RuntimeError) A value is required for :plug
在 Elixir 的網頁套件大部分都是圍繞著 Plug 這個套件/格式發展,
大家使用 plug 這個函數式的網頁處理套件為基礎來建立服務與框架。
我們現在建立一個 Plug 來設定我們的網頁伺服器要怎麼回應連線
在 lib 資料夾裡面建立新的檔案 my_plug.ex
lib/my_plug.ex
defmodule MyPlug do
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
conn
|> send_resp(200, "Hello World!")
end
end
一個 plug 模組需要有一個 init 函式與 call 函式
conn
內得到這個連線的資訊並回應目前我們使用 Plug.Conn 模組提供的 send_resp 函式
用 "Hello World!" 來回覆 http 要求
當我們有 Plug 後
就可以將他加在 children 設定裡
從 Bandit
改成 {Bandit, plug: MyPlug}
defmodule MySite do
use Application
def start(_type, _args) do
children = [{Bandit, plug: MyPlug}]
opts = [strategy: :one_for_one]
Supervisor.start_link(children, opts)
end
end
一樣透過 mix run --no-halt
啟動專案
mix run --no-halt
Compiling 1 file (.ex)
Generated my_site app
Starting Server
16:58:53.478 [info] Running MyPlug with Bandit 1.8.0 at 0.0.0.0:4000 (http)
使用瀏覽器打開 http://localhost:4000
就可以看到我們回覆的 "Hello World!" 了