hello.ex 1.3 KB

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