首页 > 代码库 > cowboy的例子
cowboy的例子
大体参考的这里,非常感谢他的例子
开发的时候先下载好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 erlblog
erlblog_app.erl
-module(erlblog_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 = routes(), Dispatch = cowboy_router:compile(Routes), Port = port(), TransOpts = [{port, Port}], ProtoOpts = [{env, [{dispatch, Dispatch}]}], cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts).stop(_State) -> ok.routes() -> [ {‘_‘, [ {"/", erlblog_handler, []} ]} ].port() -> case os:getenv("PORT") of false -> {ok, Port} = application:get_env(http_port), Port; Other -> list_to_integer(Other) end.
erlblog_handler.erl
-module(erlblog_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.
erlblog.app.src
{application, erlblog, [ {description, ""}, {vsn, "1"}, {registered, []}, {applications, [ kernel, stdlib ]}, {mod, { erlblog_app, []}}, {env, [{http_port, 8080}]} ]}.
rebar.config
% -*- erlang -*-{erl_opts, [debug_info]}.{deps, [ %如果你需要用rebar generate发布,则在这里必须写上,编译以后会在rel/xxx/lib里面有响应的库,否则运行时崩溃 {cowboy, "1.0.1", {git, "https://github.com/extend/cowboy.git", {tag, "1.0.1"}}}]}.{cover_enabled, true}.{eunit_opts, [verbose, {report,{eunit_surefire,[{dir,"."}]}}]}.{sub_dirs, ["apps/erlblog", "rel"]}.
启动
application:start(erlblog).
看看加载了哪些application
application:which_applications().
本地访问试试
http://127.0.0.1:8080
cowboy的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。