大体参考的这里,非常感谢他的例子
开发的时候先下载好cowboy的库,放到~/.erlang里面
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是rebar get-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
application:which_applications().
本地访问试试