Skip to content

Commit 6c0ddc6

Browse files
Merge pull request #1380 from renich/fix-accept-header-negotiation
Correctly parse and match HTTP Accept header parameters
2 parents 3b675ff + 9cc5ab1 commit 6c0ddc6

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

spec/amber/controller/respond_with_spec.cr

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,16 @@ module Amber::Controller
152152
context.response.headers["Content-Type"].should eq "application/json; charset=utf-8"
153153
context.response.status_code.should eq 403
154154
end
155+
156+
it "responds with json for complex Accept header with parameters" do
157+
context.response.status_code = 200
158+
expected_result = %({"type":"json","name":"Amberator"})
159+
context.request.headers["Accept"] = "application/json; charset=utf-8, text/javascript, */*; q=0.0"
160+
context.request.path = "/response/1"
161+
ResponsesController.new(context).index.should eq expected_result
162+
context.response.headers["Content-Type"].should eq "application/json; charset=utf-8"
163+
context.response.status_code.should eq 200
164+
end
155165
end
156166

157167
describe "#proc input" do

src/amber/controller/helpers/responders.cr

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ module Amber::Controller::Helpers
6565
if @requested_responses.size != 1 || @requested_responses.includes?("*/*")
6666
@requested_responses << @available_responses.keys.first
6767
end
68-
68+
6969
result = @requested_responses.find do |resp|
7070
@available_responses.keys.find { |r| r.includes?(resp) }
7171
end
@@ -96,8 +96,10 @@ module Amber::Controller::Helpers
9696
private def accepts_request_type
9797
accept = context.request.headers["Accept"]?
9898
if accept && !accept.empty?
99-
accepts = accept.split(";").first?.try(&.split(Content::ACCEPT_SEPARATOR_REGEX))
100-
return accepts if !accepts.nil? && !accepts.empty?
99+
accepts = accept.split(Content::ACCEPT_SEPARATOR_REGEX).map do |part|
100+
part.split(";").first.strip
101+
end.reject(&.empty?)
102+
return accepts unless accepts.empty?
101103
end
102104
end
103105

0 commit comments

Comments
 (0)