Skip to content

Commit 96f573e

Browse files
authored
Fix register_before_send with upgrade_adapter (#1320)
Also set status to 101.
1 parent 82cbff6 commit 96f573e

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

lib/plug/conn.ex

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ defmodule Plug.Conn do
294294
alias Plug.Conn
295295
@epoch {{1970, 1, 1}, {0, 0, 0}}
296296
@already_sent {:plug_conn, :sent}
297-
@unsent [:unset, :set, :set_chunked, :set_file]
297+
@unsent [:unset, :set, :set_upgrade, :set_chunked, :set_file]
298298

299299
@doc """
300300
Assigns a value to a key in the connection.
@@ -1471,10 +1471,11 @@ defmodule Plug.Conn do
14711471
@spec upgrade_adapter(t, atom, term) :: t
14721472
def upgrade_adapter(%Conn{adapter: {adapter, payload}, state: state} = conn, protocol, args)
14731473
when state in @unsent do
1474+
conn = run_before_send(%{conn | status: 101}, :set_upgrade)
1475+
14741476
case adapter.upgrade(payload, protocol, args) do
14751477
{:ok, payload} ->
1476-
conn = run_before_send(conn, :upgraded)
1477-
%{conn | adapter: {adapter, payload}}
1478+
%{conn | state: :upgraded, adapter: {adapter, payload}}
14781479

14791480
{:error, :not_supported} ->
14801481
raise ArgumentError, "upgrade to #{protocol} not supported by #{inspect(adapter)}"

test/plug/conn_test.exs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,9 +510,19 @@ defmodule Plug.ConnTest do
510510
test "upgrade_adapter/3 runs before_send callbacks" do
511511
conn =
512512
conn(:get, "/foo")
513-
|> register_before_send(&assign(&1, :ran_before_send, true))
513+
|> register_before_send(fn conn ->
514+
send(self(), {:state, conn.state})
515+
assert conn.status == 101
516+
517+
conn
518+
|> put_resp_header("x-test", "UPGRADE")
519+
|> assign(:ran_before_send, true)
520+
end)
514521
|> upgrade_adapter(:supported, opt: :supported)
515522

523+
assert_receive {:state, :set_upgrade}
524+
525+
assert {"x-test", "UPGRADE"} in conn.resp_headers
516526
assert conn.assigns[:ran_before_send] == true
517527
end
518528

0 commit comments

Comments
 (0)