標籤:
前段時間導讀了ranch的源碼,具體見ranch 源碼分析(一),
現在整理了下ranch架構下經典應用cowboy。
源碼地方:https://github.com/ninenines/cowboy(目前使用的是cowboy-1.0.4版本)
還是找其中最簡單的例子來入手,那就選這個static_world吧~~
首先我們來看static_world_app.erl
[[email protected] src]# cat static_world_app.erl %% Feel free to use, reuse and abuse the code in this file.%% @private-module(static_world_app).-behaviour(application).%% API.-export([start/2]).-export([stop/1]).%% API.start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {‘_‘, [ {"/", cowboy_static, {priv_file, static_world, "index.html"}}, {"/[...]", cowboy_static, {priv_dir, static_world, "", [{mimetypes, cow_mimetypes, all}]}} ]} ]), {ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [ {env, [{dispatch, Dispatch}]} ]), static_world_sup:start_link().stop(_State) -> ok.
cowboy_router.erl是路徑路由設定,我們就不看這個源碼,直接看一下結果
1> cowboy_router:compile([1> {‘_‘, [1> {"/", cowboy_static, {priv_file, static_world, "index.html"}},1> {"/[...]", cowboy_static, {priv_dir, static_world, "",1> [{mimetypes, cow_mimetypes, all}]}}1> ]}1> ]).[{‘_‘,[], [{[],[],cowboy_static,{priv_file,static_world,"index.html"}}, {[‘...‘], [],cowboy_static, {priv_dir,static_world,[], [{mimetypes,cow_mimetypes,all}]}}]}]
其實這個路由的意思是如果請求的是/,就路由在priv目錄的index.html下面,
否則就直接讀取請求的檔案。
然後我們開始看cowboy:start_http/4,就是應用啟動的主進程,
-module(cowboy).-export([start_http/4]).-export([start_https/4]).-export([start_spdy/4]).-export([stop_listener/1]).-export([set_env/3]).%%省略若干行-spec start_http(ranch:ref(), non_neg_integer(), ranch_tcp:opts(), cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) when is_integer(NbAcceptors), NbAcceptors > 0 -> ranch:start_listener(Ref, NbAcceptors, ranch_tcp, TransOpts, cowboy_protocol, ProtoOpts).-spec start_https(ranch:ref(), non_neg_integer(), ranch_ssl:opts(), cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) when is_integer(NbAcceptors), NbAcceptors > 0 -> ranch:start_listener(Ref, NbAcceptors,
%%省略若干行
可以看到這裡啟動ranch,而cowboy_protocol就是定義的使用者進程,根據ranch源碼理解,我們知道會啟動cowboy_protocol:start_link/4來處理使用者的應用資料請求
下面我們就進入cowboy的代碼世界,從cowboy_protocol:start_link/4開始
(未完待續~)
cowboy源碼分析(一)