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