From a7cf23a6a04e7cdc3f7cfe251e02e0c9a7746f34 Mon Sep 17 00:00:00 2001 From: Niko Dittmann Date: Thu, 14 Jun 2018 17:14:16 +0200 Subject: [PATCH 1/2] + extended elixir example with sendfile and chunked --- hello_world_elixir/README.md | 2 +- hello_world_elixir/lib/hello_world.ex | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/hello_world_elixir/README.md b/hello_world_elixir/README.md index 1a1b2ac..f1849d4 100644 --- a/hello_world_elixir/README.md +++ b/hello_world_elixir/README.md @@ -6,4 +6,4 @@ A tiny example Elli application. mix deps.get iex -S mix - curl localhost:3000/hello/world + curl localhost:4000/hello/world diff --git a/hello_world_elixir/lib/hello_world.ex b/hello_world_elixir/lib/hello_world.ex index ed46bf6..0a93c63 100644 --- a/hello_world_elixir/lib/hello_world.ex +++ b/hello_world_elixir/lib/hello_world.ex @@ -18,11 +18,38 @@ defmodule HelloWorld do {200, [], "Hello, World!"} end + # Return 200 and the first 20 chars of this file to GET requests to /send + defp handle(:GET, ["send"], _req) do + {:ok, [], { :file, __ENV__.file, [{:bytes, 0, 20}] } } + end + + # Return 200 and a chunked stream to GET requests to /chunked + defp handle(:GET, ["chunked"], req) do + ref = :elli_request.chunk_ref(req) + spawn_link fn -> chunk_loop(ref) end + {:chunk, [{"Content-Type", "text/event-stream"}]} + end + # Return 404 to any other requests defp handle(_, _, _req) do {404, [], "Our princess is in another castle..."} end + # start the chunk_loop with count n = 10... + defp chunk_loop ref do + chunk_loop ref, 10 + end + # close the request when n = 0 is reached... + defp chunk_loop ref, 0 do + :elli_request.close_chunk ref + end + # count down the counter n... once a second. + defp chunk_loop ref, n do + :timer.sleep(1000) + :elli_request.send_chunk(ref, ["chunk#{n}\n"]) + chunk_loop ref, n-1 + end + # Handle request events, like request completed, exception # thrown, client timeout, etc. Must return `ok'. @impl :elli_handler From ec773e741923bf6e17bc2fdbecd48525d5628705 Mon Sep 17 00:00:00 2001 From: Niko Dittmann Date: Thu, 14 Jun 2018 17:14:44 +0200 Subject: [PATCH 2/2] . updated example to elli 2.1 --- hello_world_elixir/mix.exs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hello_world_elixir/mix.exs b/hello_world_elixir/mix.exs index ac87cd6..a18e4dd 100644 --- a/hello_world_elixir/mix.exs +++ b/hello_world_elixir/mix.exs @@ -22,7 +22,7 @@ defmodule HelloWorld.MixProject do # Run "mix help deps" to learn about dependencies. defp deps do [ - {:elli, "~> 2.0"}, + {:elli, "~> 2.1"}, {:httpoison, "~> 1.0", only: [:test]} ] end