## [翻译][erlang]cowboy路由模块使用

Cowboy是基于Erlang实现的一个轻量级、快速、模块化的http web服务器。

### 1. Structure（结构）

Routes = [Host1, Host2, ... HostN].


Host1 = {HostMatch, PathsList}.
Host2 = {HostMatch, Constraints, PathsList}.


PathsList = [Path1, Path2, ... PathN].


Path1 = {PathMatch, Handler, Opts}.
Path2 = {PathMatch, Constraints, Handler, Opts}.


### 2. Match syntax（匹配语法）

（其实说了老半天，这不就是一个普通的URL嘛。URL的前半部分为主机IP或域名，这里称之为HOST，即主机。而后半部分为路径）

PathMatch1 = "/".
PathMatch2 = "/path/to/resource".

HostMatch1 = "cowboy.example.org".


PathMatch2 = "/path/to/resource".
PathMatch3 = "/path/to/resource/".


HostMatch1 = "cowboy.example.org".
HostMatch2 = "cowboy.example.org.".
HostMatch3 = ".cowboy.example.org".


PathMatch = "/hats/:name/prices".
HostMatch = ":subdomain.example.org".


HostMatch = "ninenines.:_".


PathMatch = "/hats/[page/:number]".
HostMatch = "[www.]ninenines.eu".


PathMatch = "/hats/[page/[:number]]".


PathMatch = "/hats/[...]".
HostMatch = "[...]ninenines.eu".


PathMatch = "/hats/:name/:name".


PathMatch = "/hats/:name/[:name]".


PathMatch = "/:user/[...]".
HostMatch = ":user.github.com".


PathMatch = '_'.
HostMatch = '_'.


HostMatch = "*".


### 3. Constraints（约束）

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed.

They are always given as a two or three elements tuple, where the first element is the name of the binding, the second element is the constraint's name, and the optional third element is the constraint's arguments.

The following constraints are currently defined:

• {Name, int}
• {Name, function, fun ((Value) -> true | {true, NewValue} | false)}

The int constraint will check if the binding is a binary string representing an integer, and if it is, will convert the value to integer.

The function constraint will pass the binding value to a user specified function that receives the binary value as its only argument and must return whether it fulfills the constraint, optionally modifying the value. The value thus returned can be of any type.

Note that constraint functions SHOULD be pure and MUST NOT crash.

### 4. Compilation（编译/收集）

Dispatch = cowboy_router:compile([
%% {HostMatch, list({PathMatch, Handler, Opts})}
{'_', [{'_', my_handler, []}]}
]),
%% Name, NbAcceptors, TransOpts, ProtoOpts
cowboy:start_http(my_http_listener, 100,
[{port, 8080}],
[{env, [{dispatch, Dispatch}]}]
).


### 5. Live update（热更新）

cowboy:set_env(my_http_listener, dispatch,
cowboy_router:compile(Dispatch)).


posted on 2016-11-23 14:09 Ron Ngai 阅读(...) 评论(...) 编辑 收藏