Ewebmachine.Builder.Resources
use this module will use Plug.Builder (so a plug pipeline described with the plug module_or_function_plug macro), but gives you a :resource_match local function plug which matches routes declared with the resource/2 macro and execute the plug defined by its body.
See Ewebmachine.Builder.Handlers documentation to see how to contruct these modules (in the after block)
Below a full example :
defmodule FullApi do
use Ewebmachine.Builder.Resources
if Mix.env == :dev, do: plug Ewebmachine.Plug.Debug
# pre plug, for instance you can put plugs defining common handlers
plug :resource_match
plug Ewebmachine.Plug.Run
# customize ewebmachine result, for instance make an error page handler plug
plug Ewebmachine.Plug.Send
# plug after that will be executed only if no ewebmachine resources has matched
resource "/hello/:name" do %{name: name} after
plug SomeAdditionnalPlug
content_types_provided do: ['application/xml': :to_xml]
defh to_xml, do: "<Person><name>#{state.name}</name>"
end
resource "/*path" do %{path: Enum.join(path,"/")} after
resource_exists do:
File.regular?(path state.path)
content_types_provided do:
[{state.path|>Plug.MIME.path|>default_plain,:to_content}]
defh to_content, do:
File.stream!(path(state.path),[],300_000_000)
defp path(relative), do: "#{:code.priv_dir :ewebmachine_example}/web/#{relative}"
defp default_plain("application/octet-stream"), do: "text/plain"
defp default_plain(type), do: type
end
end
Summary↑
| resource(route, list2) | Create a webmachine handler plug and use it on |
Macros
Create a webmachine handler plug and use it on :resource_match when path matches
- the route will be the matching spec (see Plug.Router.matc, string spec only)
- do_block will be called on match (so matching bindings will be available) and should return the initial state
- after_block will be the webmachine handler plug module body (wrapped with
use Ewebmachine.Builder.Handlersandplug :add_handlersto clean the declaration.
resource "/my/route/:commaid" do
id = String.split(commaid,",")
%{foo: id}
after
plug SomeAdditionnalPlug
resource_exists do: state.id == ["hello"]
end