安装 Rebar
去 Github 页面下载 Rebar 项目 , https://github.com/rebar/rebar
解压后运行 bootstrap , 就会在当前目录下面生成两个文件 : rebar.cmd 和 rebar , 分别对应了 Windows 和 Linux 的运行程序
创建 Erlang 项目
将刚刚生成的 rebar.cmd 和 rebar 复制到需要创建项目的文件夹 , 运行创建项目命令 :
# rebar create-app appid=cowboydemo
就会在当前目录下生成 src 文件夹以及 src/cowboydemo.app.src , src/cowboydemo_app.erl , src/cowboydemo_sup.erl 三个文件 ;
在当前目录新建文件 rebar.config 配置文件 , 使其依赖 1.1.2 版本的 cowboy 库 , 写入以下内容 :
{deps, [
{cowboy, "1.1.2", {git, "https://github.com/ninenines/cowboy", {tag, "1.1.2"}}}
]}.
编辑 src/cowboydemo.app.src 文件 , 添加 cowboy 相关配置如下 :
{application, cowboydemo,
[
{description, ""},
{vsn, "1"},
{registered, []},
{applications, [
kernel,
stdlib,
cowboy
]},
{mod, { cowboydemo_app, []}},
{env, [{http_port, 8080}]}
]}.
编辑 cowboydemo_app.erl 文件 , 修改如下 :
-module(cowboydemo_app).
-behaviour(application).
-export([start/2, stop/1]).
%% Application callbacks
start(_StartType, _StartArgs) ->
Routes = [
{'_', [
{"/", cowboydemo_handler, []}
]}
],
Dispatch = cowboy_router:compile(Routes),
{ok, Port} = application:get_env(http_port),
{ok, _} = cowboy:start_http(http, 100, [{port, Port}], [{env, [{dispatch, Dispatch}]}]),
cowboydemo_sup:start_link().
stop(_State) ->
ok.
在 src 目录新建 cowboydemo_handler.erl 请求处理模块文件 , 写入以下内容 :
-module(cowboydemo_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.
在 src 目录新建 cowboydemo.erl 程序入口文件 , 写入以下内容 :
-module(cowboydemo).
-export([start/0]).
start() ->
ok = application:start(crypto),
ok = application:start(asn1),
ok = application:start(public_key),
ok = application:start(ssl),
ok = application:start(ranch),
ok = application:start(cowlib),
ok = application:start(cowboy),
ok = application:start(cowboydemo).
编译项目 :
# rebar get-deps compile
启动服务器
# erl -pa ebin deps/cowboy/ebin deps/cowlib/ebin deps/ranch/ebin -s cowboydemo
查看服务器加载的模块 :
# application:which_applications().
访问服务器 :
打开连接 : http://127.0.0.1:8080/
浏览器出现 Hello World ! , 说明成功了 ;
作者 Github : tojohnonly , 博客 : EnskDeCode
本文介绍如何使用Erlang和Cowboy框架搭建一个简单的Web服务器。从安装Rebar工具开始,到创建项目、配置依赖、编写处理模块及启动服务器等步骤均有详细说明。
1355

被折叠的 条评论
为什么被折叠?



