faithandbrave / elixir-phoenix-chunked-response-example

Elixir/Phoenix chunked response example.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Elixir/Phoenix chunked response example

The repository is HTTP chunked transfer encoding example for Elixir/Phoenix. a.k.a HTTP stream response or EventSource.

chunk_demo.gif

How to Run

mix deps.get
npm install
./node_modules/brunch/bin/brunch b -p
mix phoenix.server

Open http://localhost:4000, and push START button. Then, send start.sh results to client with HTTP chunked response.

How to send chunked response

1. Dependent libraries

  • mix.exs :
def application do
  [,
   applications: [, :porcelain]]
end

defp deps do
  [,
    {:porcelain, "~> 2.0"}
  ]
end

Porcelain library is for execute shell-script.

  • package.json :
"dependencies": {
  …,
  "stream-http": "~2.4.0"
},

stream-http library is for client of chunked response.

2. Server code

  • web/controller/page_controller.ex
def start(conn, _params) do
  # set-up chunked response
  conn = conn
  |> put_resp_content_type("text/event-stream")
  |> send_chunked(200)

  # send chunk data
  conn |> chunk("a")
  conn |> chunk("b")
  conn |> chunk("c")
end

3. Client code

  • web/static/js/app.js
import "stream-http"

Add client library.

  • web/templates/page/index.html
var http = require('stream-http')
var req = http.request(options, (res) => {
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    // Received chunked-response.
    // Add output text.
    document.getElementById('chunked-output').textContent = document.getElementById('chunked-output').textContent + chunk;
  });
  res.on('end', () => {
    // Received all data.
  });
});

req.write(postData);
req.end();

Note

If you use Nginx, you should add proxy_buffering off;. Nginx cache server response, cause client receive all response at on time.

References

About

Elixir/Phoenix chunked response example.

License:MIT License


Languages

Language:Elixir 72.5%Language:JavaScript 17.2%Language:HTML 10.0%Language:CSS 0.2%Language:Shell 0.1%