cowboy作为erlang实现的高性能Web框架,应用的较多,扩展起来也方便。
Leptus增强了cowboy的restful方面功能,示例如下:
-module(hello).
-compile({parse_transform, leptus_pt}).
%%leptus callbacks
-export([init/3]).
-export([get/3]).
-export([terminate/4]).
init(_Route, _Req, State) ->
{ok, State}.
get("/", _Req, State) ->
{<<"Hello, leptus!">>, State};
get("/hi/:name", Req, State) ->
Status =ok,
Name =leptus_req:param(Req, name),
Body = [{<<"say">>, <<"Hi">>}, {<<"to">>, Name}],
{Status, {json, Body}, State}.
terminate(_Reason, _Route, _Req, _State)->
ok.
这样,就可以在几个上述源文件中专门处理restful路由功能。但leptus并未扩展websocket,通过查看源文件找到了扩展点:
在启动侦听时,由原来的
2>leptus:start_listener(http, [{'_', [{hello, undefined_state}]}]).
改为:
3> Opts = [{websocket, {"/websocket", websock_handler, []}}].
4>leptus:start_listener(http, [{'_', [{hello, undefined_state}]}], Opts).
上述Opts传到leptus.erl时,下图中新增加的部分添加了”/websocket”的websocket功能由websock_handler.erl实现。
修改后的源代码与websock_handler.erl已经上传到 https://github.com/tylerxiang/leptus_websocket.git