MacOS 搭建 cowboy 項目


搭建 CowBoy 項目

返回目錄

  1. 新建項目目錄 hello_cowboy,
    $ mkdir hello_cowboy && cd hello_cowboy
    
  2. 下載 erlang.mk 文件到項目目錄
  3. 執行以下命令,構建引導程序
    $ make -f erlang.mk bootstrap bootstrap-rel
    
  4. 編輯 makefile,來獲取和編譯Cowboy
    PROJECT = hello_cowboy
    
    DEPS = cowboy
    dep_cowboy_commit = 2.7.0
    
    DEP_PLUGINS = cowboy #加載Cowboy提供的插件
    
    include erlang.mk
    
  5. 編輯 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().
    
  6. 執行以下命令,從模板生成處理程序
    $ make new t=cowboy.http n=hello_handler
    
  7. 編輯 src/hello_handler.erl 文件,並按以下代碼修改 init/2 函數
    init(Req0, State) ->
        Req = cowboy_req:reply(200,
            #{<<"content-type">> => <<"text/plain">>},
            <<"Hello Erlang!">>,
            Req0),
        {ok, Req, State}.
    
  8. 執行命令,用以構建和啓動程序
    $ make run
    
  9. 在瀏覽器訪問 http://localhost:8080 看到 Hello Erlang 就成功了

參考

返回目錄

https://ninenines.eu/docs/en/cowboy/2.7/guide/getting_started/

發佈了41 篇原創文章 · 獲贊 2 · 訪問量 3159
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章