Closes response by default in HTTP::Server::Context#redirect (#641)

This commit is contained in:
Chao Yang 2022-06-29 05:25:40 -05:00 committed by GitHub
parent 317d086b4c
commit 9bd24caf7e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 1 deletions

View file

@ -143,4 +143,40 @@ describe "Kemal::RouteHandler" do
client_response.body.should eq("Redirecting to /login")
client_response.headers.has_key?("Location").should eq(true)
end
it "redirects and closes response in before filter" do
filter_handler = Kemal::FilterHandler.new
filter_handler._add_route_filter("GET", "/", :before) do |env|
env.redirect "/login"
end
Kemal.config.add_filter_handler(filter_handler)
get "/" do |env|
"home page"
end
request = HTTP::Request.new("GET", "/")
client_response = call_request_on_app(request)
client_response.status_code.should eq(302)
client_response.body.should eq("")
client_response.headers.has_key?("Location").should eq(true)
end
it "redirects in before filter without closing response" do
filter_handler = Kemal::FilterHandler.new
filter_handler._add_route_filter("GET", "/", :before) do |env|
env.redirect "/login", close: false
end
Kemal.config.add_filter_handler(filter_handler)
get "/" do |env|
"home page"
end
request = HTTP::Request.new("GET", "/")
client_response = call_request_on_app(request)
client_response.status_code.should eq(302)
client_response.body.should eq("home page")
client_response.headers.has_key?("Location").should eq(true)
end
end

View file

@ -17,10 +17,11 @@ class HTTP::Server
@params ||= Kemal::ParamParser.new(@request, route_lookup.params)
end
def redirect(url : String, status_code : Int32 = 302, *, body : String? = nil)
def redirect(url : String, status_code : Int32 = 302, *, body : String? = nil, close : Bool = true)
@response.headers.add "Location", url
@response.status_code = status_code
@response.print(body) if body
@response.close if close
end
def route