Skip to content

Commit

Permalink
Add more check_headers to HTTP::Server::Response (#11253)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Oct 22, 2021
1 parent 1be4fa7 commit 9a3d4a9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
28 changes: 28 additions & 0 deletions spec/std/http/server/response_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,27 @@ describe HTTP::Server::Response do
io.to_s.should eq("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nHello")
end

it "sets content type after headers sent" do
io = IO::Memory.new
response = Response.new(io)
response.print("Hello")
response.flush
expect_raises(IO::Error, "Headers already sent") do
response.content_type = "text/plain"
end
end

it "sets status code" do
io = IO::Memory.new
response = Response.new(io)
return_value = response.status_code = 201
return_value.should eq 201
response.status.should eq HTTP::Status::CREATED
response.print("Hello")
response.flush
expect_raises(IO::Error, "Headers already sent") do
response.status_code = 201
end
end

it "retrieves status code" do
Expand All @@ -175,6 +190,19 @@ describe HTTP::Server::Response do
io.to_s.should eq("HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n")
end

it "changes status and others after headers sent" do
io = IO::Memory.new
response = Response.new(io)
response.print("Foo")
response.flush
expect_raises(IO::Error, "Headers already sent") do
response.status = :not_found
end
expect_raises(IO::Error, "Headers already sent") do
response.version = "HTTP/1.0"
end
end

it "flushes" do
io = IO::Memory.new
response = Response.new(io)
Expand Down
14 changes: 12 additions & 2 deletions src/http/server/response.cr
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ class HTTP::Server
property output : IO

# :nodoc:
setter version : String
def version=(version : String)
check_headers
@version = version
end

# The status code of this response, which must be set before writing the response
# body. If not set, the default value is 200 (OK).
property status : HTTP::Status
getter status : HTTP::Status

def status=(status : HTTP::Status)
check_headers
@status = status
end

# :nodoc:
property upgrade_handler : (IO ->)?
Expand Down Expand Up @@ -60,11 +68,13 @@ class HTTP::Server

# Convenience method to set the `Content-Type` header.
def content_type=(content_type : String)
check_headers
headers["Content-Type"] = content_type
end

# Convenience method to set the `Content-Length` header.
def content_length=(content_length : Int)
check_headers
headers["Content-Length"] = content_length.to_s
end

Expand Down

0 comments on commit 9a3d4a9

Please sign in to comment.