Created
November 1, 2013 15:32
-
-
Save spiegela/7267190 to your computer and use it in GitHub Desktop.
A RESTful router example with Dynamo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Run this app from Dynamo root with: | |
| # mix run -r examples/rest.exs --no-halt | |
| # | |
| # Open a browser at URL http://localhost:3030 see the wonderment of rest. | |
| # | |
| defmodule Rest do | |
| # Cowboy Rest Handler resources | |
| # | |
| # * User guide: http://ninenines.eu/docs/en/cowboy/HEAD/guide/rest_handlers | |
| # * Reference: http://ninenines.eu/docs/en/cowboy/HEAD/manual/cowboy_rest | |
| # | |
| defmodule Handler do | |
| require :cowboy_req, as: R # Used for request body parsing. | |
| def init(_trans, _req, []) do | |
| {:upgrade, :protocol, :cowboy_rest} | |
| end | |
| # The following callbacks are all optional and have intelligent defaults as | |
| # defined int he links above. | |
| # Create new resource on POST | |
| def allow_missing_post do: true | |
| def allowed_methods(req, state) do | |
| {["GET", "OPTIONS", "PUT", "POST", "PATCH"], req, state} | |
| end | |
| # Define content types provided and their associated ProvideResource | |
| # callbacks as atoms | |
| def content_types_provided(req, state) do | |
| { [ | |
| { "application/json", :get_json }, | |
| { "text/html", :get_html }, | |
| { "text/plain", :get_plain } | |
| ], req, state } | |
| end | |
| # Define content types accepted and their associated ProvideResource | |
| # callbacks as atoms | |
| def content_types_accepted(req, state) do | |
| { [ | |
| { "application/json", :put_json} | |
| ], req, state } | |
| end | |
| # JSON ProvideResource callback | |
| def get_json(req, state) do | |
| {"{\"Hello\": \"JSON!\"}", req, state} | |
| end | |
| # HTML ProvideResource callback | |
| def get_html(req, state) do | |
| {"<ul><li>Hello</li><li>HTML!</li></ul>", req, state} | |
| end | |
| # Plain ProvideResource callback | |
| def get_plain(req, state) do | |
| {"Hello Plain!", req, state} | |
| end | |
| # Plain AcceptResource callback | |
| def put_json(req, state) do | |
| { :ok, body, req } = R.body req | |
| verb = case R.method(req) do | |
| { "PUT", _ } -> "PUTTING" | |
| { "POST", _ } -> "POSTING" | |
| { "PATCH", _ } -> "PATCHING" | |
| end | |
| IO.puts "#{verb} WITH: #{body}" | |
| {true, req, state} | |
| end | |
| end | |
| defmodule Router do | |
| use Dynamo | |
| use Dynamo.Router | |
| config :server, | |
| port: 3030, | |
| dispatch: [ | |
| { :_, | |
| [ | |
| {:_, Handler, []} | |
| ] | |
| } | |
| ] | |
| end | |
| end | |
| Rest.Router.start_link | |
| Rest.Router.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment