Hi,
I’m new to Elixir and Phoenix and want to build a small microservice to provide a small HMAC protected json api. For the HMAC verification I need to calculate the hash of the request body.
I can read the body with the plug function “read_body(conn, opts)” and calculate the hash. But in the documentation and several other resources it is said that I can only read the body once (which makes sense to me because the data is read from the underlying tcp connection).
https://hexdocs.pm/plug/Plug.Conn.html#read_body/2
Because the request body can be of any size, reading the body will only work once, as Plug will not cache the result of these operations. If you need to access the body multiple times, it is your responsibility to store it. Finally keep in mind some plugs like Plug.Parsers may read the body, so the body may be unavailable after being accessed by such plugs.
I’m a little bit irritated because when I invoke “read_body(…)” multiple times in the plug pipeline, I always get the correct body content. Is this correct?
And if calling “read_body” more than once is error prone, how can I read the body, store it with the connection and call other plugs (e.g. parse-json) which read the body as well? The documentation tells me to do so, but I don’t known how to implement this.