在Erlang中,inets庫可用于在Erlang中構建web服務器。讓我們看看Erlang中用于web編程的一些函數(shù)。可以實現(xiàn)HTTP服務器(也稱為httpd)來處理HTTP請求。
服務器實現(xiàn)了許多特性,例如-
安全套接字層(SSL)
Erlang腳本接口(ESI)
通用網(wǎng)關接口(CGI)
用戶身份驗證(使用Mnesia,Dets或純文本數(shù)據(jù)庫)
通用日志文件格式(支持或不支持disk_log(3))
URL別名
動作映射
目錄列表
第一項工作是通過命令啟動Web庫。
inets:start()
下一步是實現(xiàn)inets庫的start函數(shù),以便實現(xiàn)web服務器。
以下是在Erlang中創(chuàng)建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_root和document_root是強制性的參數(shù)。
以下是上述程序的輸出。
{ok,<0.42.0>}
要在 Erlang 實現(xiàn) Hello world web 服務器,請執(zhí)行以下步驟-
Step 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>" ]).
Step 2?如下運行代碼。編譯上面的文件,然后在erl中運行以下命令。
c(helloworld).
您將獲得以下輸出。
{ok,helloworld}
下一個命令是-
inets:start().
您將獲得以下輸出。
ok
下一個命令是-
helloworld:start().
您將獲得以下輸出。
{ok,<0.50.0>}
Step 3?您現(xiàn)在可以訪問url- http://localhost:8081/erl/hello_world:service。