cowboy의 예

5553 단어 예.
대체로 참고한여기. 그의 예에 대단히 감사합니다
 
개발할 때 먼저 cowboy의 라이브러리를 다운로드하여 ~/.안.
code:add_pathz("/Users/mmc/erlang/3rd_libs/cowboy/ebin/").
code:add_pathz("/Users/mmc/erlang/3rd_libs/cowboy/deps/ranch/ebin/").
code:add_pathz("/Users/mmc/erlang/3rd_libs/cowboy/deps/cowlib/ebin/").

ranch와cowlib는rebarget-deps에서 얻은 거예요.
 
건립 공사
rebar-creator create-app testCowboy

 
testCowboy_app.erl
-module(testCowboy_app).
-behaviour(application).

-export([start/2, stop/1]).

-define(C_ACCEPTORS,  100).

start(_StartType, _StartArgs) ->
    ok = application:start(crypto),
    ok = application:start(cowlib),
    ok = application:start(ranch),
    ok = application:start(cowboy),

    Routes    = route_helper:get_routes(),
    Dispatch  = cowboy_router:compile(Routes),
    Port      = get_port(),
    TransOpts = [{port, Port}],
    ProtoOpts = [{env, [{dispatch, Dispatch}]}],
    cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts).

stop(_State) ->
    ok.

get_port() ->
    case os:getenv("PORT") of
        false ->
            {ok, Port} = application:get_env(http_port),
            Port;
        Other ->
            list_to_integer(Other)
    end.

 
path_helper.erl
-module(path_helper).

-export([get_path/1]). get_path(ExtraPath)-> {ok,CurrentPath} = file:get_cwd(), Path = string:concat(CurrentPath,"/"), string:concat(Path,ExtraPath).

 
route_helper.erl
-module(route_helper).

-export([get_routes/0]).

get_routes() ->
    StaticPath = path_helper:get_path("../static/"),
    [
        {'_', [
            {"/", test_handler, []},
            %                ,        
            {"/static/[...]", cowboy_static, {dir, StaticPath}}
        ]}
    ].

 
test_handler.erl
-module(test_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
    {ok, Req, undefined}.

handle(Req, State) ->
    {ok, Req2} = cowboy_req:reply(200, [], <<"Hello world!">>, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.

 
testCowboy.app.src
{application, testCowboy,
 [
  {description, ""},
  {vsn, "1"},
  {registered, []},
  {applications, [
                  kernel,
                  stdlib
                 ]},
  {mod, { testCowboy_app, []}},
  {env, [{http_port, 8080}]}
 ]}.

 
부팅
application:start(testCowboy).

어떤 애플리케이션이 로드되었는지 확인
application:which_applications().

 
로컬 액세스 시도
http://127.0.0.1:8080

좋은 웹페이지 즐겨찾기