iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0

接續前一篇的 application
現在要讓 application 啟動的時候,也開啟網頁伺服器
目前 Elixir 有兩個常用的網頁伺服器 (web server) 套件可以選擇

  • bandit 比較新的,目前 Phoenix 框架預設的網頁伺服器
  • cowboy erlang 寫的網頁伺服器,舊的 Phoenix 預設

在這邊我們安裝並使用 bandit

mix.exsdeps 函式加上 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

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 函式

  • init 的變數為 supervisor 使用的 options,目前不需要調整,直接回傳 options 即可
  • 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!" 了


上一篇
Elixir 的 Application (應用程式)
系列文
通勤看手機就可讀懂的 Elixir 語言入門教學26
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言