Is there a Sinatra style web framework for Erlang?

2019-01-31 14:57发布

问题:

I programmed in Ruby and Rails for quite a long time, and then I fell in love with the simplicity of the Sinatra framework which allowed me to build one page web applications.

Is there a web framework like Sinatra available for Erlang? I tried Erlyweb but it seems far too heavyweight.

回答1:

You could achieve something minimal with mochiweb:

start() ->
  mochiweb_http:start([{'ip', "127.0.0.1"}, {port, 6500},
                       {'loop', fun ?MODULE:loop/1}]).
                           % mochiweb will call loop function for each request

loop(Req) ->
  RawPath = Req:get(raw_path),
  {Path, _, _} = mochiweb_util:urlsplit_path(RawPath),   % get request path

  case Path of                                           % respond based on path
    "/"  -> respond(Req, <<"<p>Hello World!</p>">>);
    "/a" -> respond(Req, <<"<p>Page a</p>">>);
    ...
    _    -> respond(Req, <<"<p>Page not found!</p>">>)
  end.

respond(Req, Content) ->
  Req:respond({200, [{<<"Content-Type">>, <<"text/html">>}], Content}).

If you need advanced routing, you will have to use regex's instead of a simple case statement.



回答2:

Have a look at webmachine. It has a very simple but powerful dispatch mechanism. You simply have to write a resource module, point your URIs to it and your service is automatically HTTP compliant.



回答3:

You may want to take a look at Axiom (disclosure: it's my own project). It is largely inspired by Sinatra, built on top of Cowboy and offers a lot of the features, Sinatra does.

A simple example:

-module(my_app).
-export([start/0, handle/3]).

start() ->
    axiom:start(?MODULE).

handle('GET', [<<"hi">>], _Request) ->
    <<"Hello world!">>.

This handles GET /hi and returns Hello World!.

Take a look at the README for a documentation of it's features.



回答4:

You might be interested in Rusty Klophaus' nitrogen framework. It's really lightweight and is ideal for really dynamic single page sites.



回答5:

May be this example (see REST SUPPORT) using misultin, looks like sinatra :

  • http://code.google.com/p/misultin/wiki/ExamplesPage