hello.ex 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. defmodule Hello do
  2. def start(_type, _args) do
  3. dispatch = :cowboy_router.compile([
  4. { :_,
  5. [
  6. {"/json", JsonHandler, []},
  7. {"/plaintext", PlaintextHandler, []}
  8. ]}
  9. ])
  10. { :ok, _ } = :cowboy.start_http(:http,
  11. 5000,
  12. [{:port, 8080}],
  13. [{ :env, [{:dispatch, dispatch}]}]
  14. )
  15. end
  16. end
  17. defmodule JsonHandler do
  18. def init(_type, req, []) do
  19. {:ok, req, :no_state}
  20. end
  21. def handle(request, state) do
  22. Poison.encode!(%{message: "Hello, World!"})
  23. { :ok, reply } = :cowboy_req.reply(200,
  24. [{"content-type", "application/json"}],
  25. Poison.encode!(%{:message => "Hello, World!"}),
  26. request)
  27. { :ok, reply, state }
  28. end
  29. def terminate(reason, request, state) do
  30. :ok
  31. end
  32. end
  33. defmodule PlaintextHandler do
  34. def init(_type, req, []) do
  35. {:ok, req, :no_state}
  36. end
  37. def handle(request, state) do
  38. Poison.encode!(%{message: "Hello, World!"})
  39. { :ok, reply } = :cowboy_req.reply(200,
  40. [{"content-type", "text/plain"}],
  41. "Hello, World!",
  42. request)
  43. { :ok, reply, state }
  44. end
  45. def terminate(reason, request, state) do
  46. :ok
  47. end
  48. end