Erlang - Web程式設計



在 Erlang 中,inets 庫 可用於構建 Erlang 中的 Web 伺服器。讓我們看看 Erlang 中可用於 Web 程式設計的一些函式。可以實現 HTTP 伺服器,也稱為 httpd,來處理 HTTP 請求。

伺服器實現了眾多功能,例如:

  • 安全套接字層 (SSL)
  • Erlang 指令碼介面 (ESI)
  • 通用閘道器介面 (CGI)
  • 使用者身份驗證(使用 Mnesia、Dets 或純文字資料庫)
  • 通用日誌檔案格式(帶或不帶 disk_log(3) 支援)
  • URL 別名
  • 操作對映
  • 目錄列表

第一步是透過命令啟動 Web 庫。

inets:start()

下一步是實現 inets 庫的啟動函式,以便可以實現 Web 伺服器。

以下是建立 Erlang 中的 Web 伺服器程序的示例。

例如

-module(helloworld). 
-export([start/0]). 

start() ->
   inets:start(), 
   Pid = inets:start(httpd, [{port, 8081}, {server_name,"httpd_test"}, 
   {server_root,"D://tmp"},{document_root,"D://tmp/htdocs"},
   {bind_address, "localhost"}]), io:fwrite("~p",[Pid]).

關於上述程式,需要注意以下幾點。

  • 埠號必須唯一,並且不能被任何其他程式使用。httpd 服務 將在此埠號上啟動。

  • server_rootdocument_root 是必填引數。

輸出

以下是上述程式的輸出。

{ok,<0.42.0>}

要在 Erlang 中實現Hello world Web 伺服器,請執行以下步驟:

步驟 1 - 實現以下程式碼:

-module(helloworld). 
-export([start/0,service/3]). 

start() ->
   inets:start(httpd, [ 
      {modules, [ 
         mod_alias, 
         mod_auth, 
         mod_esi, 
         mod_actions, 
         mod_cgi, 
         mod_dir,
         mod_get, 
         mod_head, 
         mod_log, 
         mod_disk_log 
      ]}, 
      
      {port,8081}, 
      {server_name,"helloworld"}, 
      {server_root,"D://tmp"}, 
      {document_root,"D://tmp/htdocs"}, 
      {erl_script_alias, {"/erl", [helloworld]}}, 
      {error_log, "error.log"}, 
      {security_log, "security.log"}, 
      {transfer_log, "transfer.log"}, 
      
      {mime_types,[ 
         {"html","text/html"}, {"css","text/css"}, {"js","application/x-javascript"} ]} 
   ]). 
         
service(SessionID, _Env, _Input) -> mod_esi:deliver(SessionID, [ 
   "Content-Type: text/html\r\n\r\n", "<html><body>Hello, World!</body></html>" ]).

步驟 2 - 如下執行程式碼。編譯上述檔案,然後在erl中執行以下命令。

c(helloworld).

您將獲得以下輸出。

{ok,helloworld}

下一個命令是:

inets:start().

您將獲得以下輸出。

ok

下一個命令是:

helloworld:start().

您將獲得以下輸出。

{ok,<0.50.0>}

步驟 3 - 您現在可以訪問 url - https://:8081/erl/hello_world:service

廣告