”;
In Erlang, the inets library is available to build web servers in Erlang. Let’s look at some of the functions available in Erlang for web programming. One can implement the HTTP server, also referred to as httpd to handle HTTP requests.
The server implements numerous features, such as −
- Secure Sockets Layer (SSL)
- Erlang Scripting Interface (ESI)
- Common Gateway Interface (CGI)
- User Authentication (using Mnesia, Dets or plain text database)
- Common Logfile Format (with or without disk_log(3) support)
- URL Aliasing
- Action Mappings
- Directory Listings
The first job is to start the web library via the command.
inets:start()
The next step is to implement the start function of the inets library so that the web server can be implemented.
Following is an example of creating a web server process in Erlang.
For example
-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]).
The following points need to be noted about the above program.
-
The port number needs to be unique and not used by any other program. The httpd service would be started on this port no.
-
The server_root and document_root are mandatory parameters.
Output
Following is the output of the above program.
{ok,<0.42.0>}
To implement a Hello world web server in Erlang, perform the following steps −
Step 1 − Implement the following code −
-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/htmlrnrn", "<html><body>Hello, World!</body></html>" ]).
Step 2 − Run the code as follows. Compile the above file and then run the following commands in erl.
c(helloworld).
You will get the following output.
{ok,helloworld}
The next command is −
inets:start().
You will get the following output.
ok
The next command is −
helloworld:start().
You will get the following output.
{ok,<0.50.0>}
Step 3 − You can now access the url – http://localhost:8081/erl/hello_world:service.
”;