Erlang/Elixir 类似 Ruby Grape 项目的 Elixir RESTFul 框架 Maru

falood · January 10, 2015 · Last by seamon replied at May 25, 2015 · 8246 hits
Topic has been selected as the excellent topic by the admin.

自从用 grape 开发过 API,从此爱不释手,从开坑 maru 到现在也一年多了,从 elixir 0.11 一路跟过来,也遇到了很多问题。现在 elixir 渐渐成熟,elixir 的 web 项目也越来越多,借此推广下这个框架 :D

为什么会有 maru

学习 elixir 的人应该都知道 phoenix ,毫无疑问 phoenix 是个非常棒的 elixir web 框架,但就像 ruby 中有 rails 并没有影响 sinatragrape 这种新框架的出现。maru 也是基于 plug 开发的框架,可以无缝拉入 phoenix 作为 restful server。

maru 有什么特点

maru 的灵感来源是 grape,甚至大多数的地方在语法层面上保持一致,如果熟悉 grape 是非常容易上手的,这里简单介绍一下 maru 的 DSL

路由

以下路由方案对应了 '/users/:id' 这个 url 的 get, postdelete 方法:

resource :users do
  route_param :id do
    get do
      %{user: XXX} |> json
    end

    post do
      %{result: :success} |> json
    end

    delete do
      %{result: :success} |> json
    end
  end
end

同时 resource 是可以嵌套的,也支持 getpost 等宏的路径参数,例如:

resources :level1 do
  resource :level2 do
    get do
      XXX
    end
  end
end

get "/users/:id" do
  XXX
end

参数

参数的用法同样类似 grape,但根据 elixir 的语言改变了一些名称,比如说 grape 里的 Hash 改成了 Map,Symble 改成了 Atom 等。

params do
  requires :age,    type: Integer, values: 18..65
  requires :sex,    type: Atom, values: [:male, :female], default: :female
  group    :name,   type: Map do
    requires :first_name
    requires :last_name
  end
  optional :intro,  type: String, regexp: ~r/^[a-z]+$/
  optional :avatar, type: File
  optional :avatar_url, type: String
  exactly_one_of [:avatar, :avatar_url]
end
post do
  IO.inspect params
end

在 phoenix 框架中使用 maru

  1. mix.exs 的 deps 里加入 elixir {:maru, github: "falood/maru"}
  2. 编写 maru router ```elixir defmodule MyAPP.API do use Maru.Router

get do "It Works!" |> text end end

3. endpoint.ex 里 加一行
```elixir
plug Maru.Plugs.Forword, at: "/api", to: MyAPP.API

这样就把 /api 下的请求 forward 到 maru 了,其它的请求继续走 phoenix,这里有个示例。

PS. 目前 hex 里的最新版是 0.2.7,forword 的特性已经进入 master 分支,会在 hex 0.2.8 中发布。

总结

更多的特性就不在这里写了,非常欢迎喜欢 grape 的童鞋试用 maru ,也非常欢迎拍砖或贡献代码。

PS. 希望 github 上的 issue 和 commit 都使用英文。不是为了装 B,虽然我自己英文也比较烂,但中文的 commit 过多,会导致无法与国外的牛人交流,望理解。

上面的 DSL 和 Ruby、Grape 巨像

#1 楼 @huacnlee 就是照着那个实现的呀 :D 不过本来 elixir 很多语法都和 ruby 很像

楼主是个牛人!我项!!!!!

感谢大家的支持!elixir 本身就是从 ruby 社区起源的,大家业余时间可以玩票下,很容易上手的!

一直在找类似 restx.io 的框架

#12 楼 @zeeler 那个 API 测试的页面,我有想法要加一个的说!有啥其它的很亮的点么 :D

#13 楼 @falood 其实 API 主要包含接口定义、测试页面和文档页面,然后还有 cache 层就行,不建议把业务逻辑也放在里面,建议单独拿出来做

#14 楼 @zeeler 我想做那个东西就是个文档页面,只不过算是一个活的文档页面吧 :D,看 python 和 ruby 的好多框架都带这种东西

Erlang 未来在企业领域应该会有很有市场

看了一下,挺不错的。已 watch+star,继续努力。

You need to Sign in before reply, if you don't have an account, please Sign up first.