Response
Status DSL
status 200
↓ ↓ ↓
Plug.Conn.put_status(200)
Content_type DSL
content_type "application/json"
↓ ↓ ↓
conn = conn |> Plug.Conn.put_resp_content_type("application/json")
Header DSL
headers
↓ ↓ ↓
conn.req_headers |> Enum.into %{}
header(key, nil)
↓ ↓ ↓
conn = conn |> Plug.Conn.delete_resp_header(key)
header(key, value)
↓ ↓ ↓
conn = conn |> Plug.Conn.put_resp_header(key, value)
Assign DSL
assigns
↓ ↓ ↓
conn.assigns
assign(key, value)
↓ ↓ ↓
conn = conn |> Plug.Conn.assign(key, value)
Make Response
Maru.Response protocol is defined to process response with two function: content_type and resp_body.
By default, String will be return directly with text/plain, and any other struct will be processed by Poison.encode! with application/json.
You can use a custom struct like this:
defmodule User do
defstruct name: nil, age: nil, password: nil
end
defimpl Maru.Response, for: User do
def content_type(_) do
"application/json"
end
def resp_body(user) do
%{name: user.name, age: user.age} |> Poison.encode!
end
end
defmodule API do
use Maru.Router
get do
%User{name: "falood", age: "25", password: "123456"}
end
end
If you're using maru_entity, present may be the best way to make response.
get do
users = User.all
present users, with: UserEntity # => [%{name: "name1"}, %{name: "name2"}]
end
or
get do
users = User.all
present :data, users, with: UserEntity # => %{data: [%{name: "name1"}, %{name: "name2"}]}
end
Redirecting
You can redirect to a new url temporarily (302) or permanently (301).
redirect '/statuses'
redirect '/statuses', permanent: true
Updated less than a minute ago
