When I first started using Erlang it took a fair bit of trial and error to create a server that generated dynamic HTTP content. The main problem is the lack of good tutorials out there for doing these kinds of things. The documentation that comes with Erlang is good for reference, but is not that helpful if you're just learning the language.
In particular, there didn't seem to be a basic "Hello World" example for building web applications. So here's my attempt to fix that. Below is some code that starts up an HTTP server, and dynamically generates a simple "Hello, World" page:
-module(hello_world).
-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,"hello_world"},
{server_root,"log"},
{document_root,"www"},
{erl_script_alias, {"/erl", [hello_world]}},
{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>"
]).
To run it, save the code to a file called
hello_world.erl, and create two subdirectories next to it called "www" and "log" (these subdirectories can be empty, but they need to be there for the server to start). Then fire up erl and run the following three commands:
Eshell V5.6 (abort with ^G)
1> c(hello_world).
{ok,hello_world}
2> inets:start().
ok
3> hello_world:start().
{ok,<0.51.0>}
You should now be able to browse to the following URL and see your message (if for some reason it doesn't work for you please let me know):
http://localhost:8081/erl/hello_world:service
For more info, here are the reference docs for the relevant Erlang modules:
0 comments:
Post a Comment