In a web application, the browser sends a request, the server calls a function and returns a response. Each request is independent. This maps very well to the functional programming paradigm; hence, we continue our experiments with Erlang. Webmachine is a REST toolkit in Erlang on top of mochiweb. As an illustration, we will start with the demo application included with webmachine and add a form to it. The form will allow us to add a key/value pair or get all the key/value pairs which have some value. Getting startedWe will be using the packages included in the Fedora 20 repositories. Make a copy of the demo in /usr/share/doc/erlang-webmachine/demo/. As the demo depends on an earlier version of webmachine, some extra steps may be needed. In the demo directory, we do the following:
The application failed to start with messages which include phrases like “not_started,ssl”. To overcome the errors, start function in src/webmachine_demo.erl was modified as follows:
Now compilation and execution of start.sh should go through properly. Browsing http://localhost:8000/demo should show a welcome message. Adding FunctionalityThe mapping between the url paths and the modules is specified in file priv/dispatch.conf. Suppose the additional functionality is to be accessed by from the url path /key. The priv/dispatch.conf will become:
The code needed for this functionality will be in src/webmachine_key_resource.erl:
The resource module needs at least two functions by default, init and to_html. The init function is used to specify the context needed for this resource. Webmachine passes it as is to various functions. The default name of the function for the GET request is to_html. In case the key field is empty or not defined, the function does nothing; otherwise, it inserts the key/value pair in a table. It then queries the table for all records which have a the desired value and displays the result in a template. The templates/webapp.dtl template is similar to the one explained in the previous article:
For completeness, the code in src/db.erl for storing and querying data from mnesia is as follows:
Finally, mnesia needs to be started. Add the following lines at the start of the start function in src/webmachine_demo.erl:
Compile and run start.sh. Now browse http://localhost:8000/key and explore the form. Getting used to Erlang is not difficult. Functional programming is fun. Referenceshttps://github.com/basho/webmachine/wiki http://www.erlang.org/doc/apps/mnesia/Mnesia_chap2.html http://en.wikiversity.org/wiki/Web_Development_with_Webmachine_for_Erlang |
Exploring Software >