Working example for Erlang Server Interface
I am trying to make Erlang's Inets mode_esi work and run some function. So, far, I did not succeed. Can someone post a minimal example of how to run Inets so that a url like http:localho开发者_如何学Cst:8099/esi/my_mod:foo
will invoke the method my_mod:foo/3
?
Addition: I have started inets with these commands:
inets:start(),
inets:start(httpd, [{port, 8099}, {server_name, "localhost"}, {document_root, "."},
{server_root, "."}, {erl_script_alias, {"/esi", [my_esi, io]}}]).
The module is:
-module(my_esi).
-export([foo/3]).
foo(Sid, Env, In) -> mod_esi:deliver(Sid, ["bla"]).
But browsing to http://localhost:8099/esi/my_esi:foo
result in an error message.
To clarify what has already been said, I'll give a working example (from the ground up). This is to help those who came here from google, mostly because it's how I found it ;)
First, create the module:
# filename: my_esi.erl
-module(my_esi).
-export([foo/3,bar/3]).
foo(Sid, Env, In) -> mod_esi:deliver(Sid, ["foo"]).
bar(Sid, Env, In) -> mod_esi:deliver(Sid, ["bar"]).
Save it, then compile it:
erlc my_esi.erl
You'll now have my_esi.beam
Then run the shell from bash
erl
Within the shell type the following:
inets:start().
{Httpd_State,Httpd_Pid} = inets:start(httpd, [{port, 8099}, {server_name, "localhost"}, {document_root, "."}, {modules,[mod_esi]},{server_root, "."}, {erl_script_alias, {"/esi", [my_esi, io]}}]).
The important part here is:
{modules,[mod_esi]}
If you need other modules, load them by appending them to the list.
To clarify how/why:
I will first admit that it does seems a bit strange at first, and that the documentation was less helpful than I had hoped. However, I realised that:
modules() -> [atom()]
becomes:
{modules, [mod_access, mod_esi, ..., etc.]}
Hope it helps someone :)
I've solved it myself. For some reason, beyond my understanding, the exact same code worked when I invoked Inets with a configuration file (a modified version of inets/examples/server_root/conf/8080.conf
). I suppose that the example file includes a more complete list of properties that Inets required than what I listed in inets:start(httpd, [...])
. If anyone encounters Inets problem in the future, my advice is to start with the example configuration.
Ok, here goes:
- set
{erl_script_alias, {"/esi", [my_mod]}}
for theinets
web server, so the module is accepted. Write
my_mod
. Something like:-module(my_mod). -export([foo/3]). foo(SessID, _Env, _Input) -> mod_esi:deliver(SessID, ["Data ", <<"as">>, " an iolist"]).
- Make sure
mod_esi
is part ofinets
section called module:{modules, [.., mod_esi, ..}}
- This step is very important: Breathe 3 times, recite the holy words "I pray to thee, inets, that you will work this time". Cross your fingers.
- Drink a cup of coffee. Tea will not do. It has to be coffee.
- Enjoy your web server.
精彩评论