Basic Usage
Install
- Create a new application
mix new my_app
- Add maru to your
mix.exs
dependencies:
defp deps do
[
{:maru, "~> 0.13"},
{:cowboy, "~> 2.3"},
# Optional dependency, you can also add your own json_library dependency
# and config with `config :maru, json_library, YOUR_JSON_LIBRARY`.
{:jason, "~> 1.0"},
]
end
- List
:maru
as your application dependencies: (you don't need do this for elixir ~> 1.4)
def application do
[ applications: [:maru] ]
end
Config
config :my_app, MyAPP.Server,
adapter: Plug.Adapters.Cowboy2,
plug: MyAPP.API,
scheme: :http,
port: 8880
config :my_app,
maru_servers: [MyAPP.Server]
Basic Server
defmodule MyAPP.Server do
use Maru.Server, otp_app: :my_app
end
# Add MyAPP.Server to Your Supervisor Tree
defmodule MyApp.Supervisor do
use Supervisor
def init(_arg) do
children = [
MyAPP.Server
]
Supervisor.init(children, strategy: :one_for_one)
end
end
Basic Router
defmodule MyAPP.Router.Homepage do
use MyAPP.Server
get do
json(conn, %{ hello: :world })
end
end
defmodule MyAPP.API do
use MyAPP.Server
plug Plug.Parsers,
pass: ["*/*"],
json_decoder: Poison,
parsers: [:urlencoded, :json, :multipart]
mount MyAPP.Router.Homepage
rescue_from :all do
conn
|> put_status(500)
|> text("Server Error")
end
end
Run server
$ mix deps.get
$ iex -S mix
Erlang/OTP 17 [erts-6.4] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.0.4) - press Ctrl+C to exit (type h() ENTER for help)
17:42:17.691 [info] Running Elixir.API with Cowboy on http://127.0.0.1:8880
iex(1)>
$ curl 127.0.0.1:8880
{"hello":"world"}
Generate routes documents
$ MIX_ENV=dev mix maru.routes
Updated about 6 years ago