Skip to content

Allow send_resp to be used without a body #1275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/plug/conn.ex
Original file line number Diff line number Diff line change
Expand Up @@ -590,10 +590,12 @@ defmodule Plug.Conn do
## Examples

Plug.Conn.send_resp(conn, 404, "Not found")
Plug.Conn.send_resp(conn, 204)

"""
@spec send_resp(t, status) :: t | no_return
@spec send_resp(t, status, body) :: t | no_return
def send_resp(%Conn{} = conn, status, body) do
def send_resp(%Conn{} = conn, status, body \\ "") do
conn |> resp(status, body) |> send_resp()
end

Expand Down
10 changes: 10 additions & 0 deletions test/plug/conn_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ defmodule Plug.ConnTest do
assert get_resp_cookies(conn)["hello"] == %{value: "world"}
end

test "send_resp/2 sets the body to empty string" do
conn = conn(:get, "/foo")
assert conn.state == :unset
assert conn.resp_body == nil
conn = send_resp(conn, 204)
assert conn.status == 204
assert conn.resp_body == ""
assert conn.state == :sent
end

test "send_resp/1 raises if the connection was unset" do
conn = conn(:get, "/goo")

Expand Down
8 changes: 4 additions & 4 deletions test/plug/telemetry_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ defmodule Plug.TelemetryTest do
use Plug.Builder

plug Plug.Telemetry, event_prefix: [:pipeline], extra_options: :hello
plug :send_resp, 200
plug :send_response, 200

defp send_resp(conn, status) do
defp send_response(conn, status) do
Plug.Conn.send_resp(conn, status, "Response")
end
end
Expand All @@ -26,13 +26,13 @@ defmodule Plug.TelemetryTest do

plug Plug.Telemetry, event_prefix: [:crashing, :pipeline]
plug :raise_error
plug :send_resp, 200
plug :send_response, 200

defp raise_error(_conn, _) do
raise "Crash!"
end

defp send_resp(conn, status) do
defp send_response(conn, status) do
Plug.Conn.send_resp(conn, status, "Response")
end
end
Expand Down