Plug.Parser custom body_reader example: why an array?

The documentation for :body_reader in Plug.Parsers includes this example:

defmodule CacheBodyReader do
  def read_body(conn, opts) do
    {:ok, body, conn} = Plug.Conn.read_body(conn, opts)
    conn = update_in(conn.assigns[:raw_body], &[body | (&1 || [])])
    {:ok, body, conn}
  end
end

Why does this example use

conn = update_in(conn.assigns[:raw_body], &[body | (&1 || [])])

rather than

conn = Plug.Conn.assign(conn, :raw_body, body)

Does the assign need to be an array? Are there other plugs that use conn.assigns[:raw_body], and don’t want it to be overwritten?

Few things:

  • This is list, not array. There is huge difference between these two structures. The nearest equivalent of “arrays” from other languages would be tuple, not list.
  • See that original code is appending data to the field, not just replacing it as you do in your code.
3 Likes

I guess the missing piece here is that the raw body might be parsed in multiple steps making the read_body/2 function be called multiple times.

4 Likes