elixir-plug / plug

Compose web applications with functions
https://hex.pm/packages/plug
Other
2.84k stars 582 forks source link

Add register_before_chunk/2 function #1153

Closed feynmanliang closed 1 year ago

feynmanliang commented 1 year ago

I am building a caching plug with cache keys from conn.body_params and cache values from the conn's response.

We currently have Plug.Conn.register_before_send/2 to register a callback before sending a response. This works great for caching conn.resp_body when it is available.

However, for server sent events (SSEs) and chunked responses more generally, it seems like run_before_send is only run on the initial Plug.Conn.send_chunked/2 call before any chunks are sent. At this moment, conn.resp_body is empty so an empty value is cached.

What we would like to do is to append to the cache as individual chunks are sent using Plug.Conn.chunk/2, but I do not currently see any lifecycle callback available to do this. I am wondering if there is another way to achieve this, and if not would adding a register_before_chunk/2 method to register callbacks (say inside conn.private[:before_send]) which receive the conn and chunk passed to each chunk/2 call be valuable?

I am happy to help contribute the implementation if it is desired.

whatyouhide commented 1 year ago

Closing in favor of the PR #1154.