文章目錄
搭建 CowBoy 項目
- 新建項目目錄 hello_cowboy,
$ mkdir hello_cowboy && cd hello_cowboy
- 下載 erlang.mk 文件到項目目錄
- 執行以下命令,構建引導程序
$ make -f erlang.mk bootstrap bootstrap-rel
- 編輯 makefile,來獲取和編譯Cowboy
PROJECT = hello_cowboy DEPS = cowboy dep_cowboy_commit = 2.7.0 DEP_PLUGINS = cowboy #加載Cowboy提供的插件 include erlang.mk
- 編輯 src/hello_erlang_app.erl 文件,將代碼添加到start/2函數中
start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [{"/", hello_handler, []}]} ]), {ok, _} = cowboy:start_clear(my_http_listener, [{port, 8080}], #{env => #{dispatch => Dispatch}} ), hello_erlang_sup:start_link().
- 執行以下命令,從模板生成處理程序
$ make new t=cowboy.http n=hello_handler
- 編輯 src/hello_handler.erl 文件,並按以下代碼修改 init/2 函數
init(Req0, State) -> Req = cowboy_req:reply(200, #{<<"content-type">> => <<"text/plain">>}, <<"Hello Erlang!">>, Req0), {ok, Req, State}.
- 執行命令,用以構建和啓動程序
$ make run
- 在瀏覽器訪問 http://localhost:8080 看到 Hello Erlang 就成功了
參考
https://ninenines.eu/docs/en/cowboy/2.7/guide/getting_started/