Skip to content

Commit

Permalink
Sponge: properly encode POST data
Browse files Browse the repository at this point in the history
Should fix lobsters#1081
  • Loading branch information
jcs committed Sep 25, 2024
1 parent f512ae4 commit da312e7
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion extras/sponge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def fetch(url, method = :get, fields = nil, raw_post_data = nil, headers = {}, l
post_data = raw_post_data
send_headers["Content-Type"] = "application/x-www-form-urlencoded"
else
post_data = fields.map { |k, v| "#{k}=#{v}" }.join("&")
post_data = encode_fields(fields)
end

send_headers["Content-Length"] = post_data.length.to_s
Expand Down Expand Up @@ -263,4 +263,26 @@ def dputs(string)
puts string
end
end

def encode_fields(fields)
fields.map { |k, v|
if v.is_a?(Hash)
# :user => { :name => "hi", :age => "1" }
# becomes
# user[hame]=hi and user[age]=1
v.map { |vk, vv|
[CGI.escape("#{k}[#{vk}]"), CGI.escape(vv.to_s)].join("=")
}
elsif v.is_a?(Array)
# :user => [ "one", "two" ]
# becomes
# user[]=one and user[]=two
v.map { |vv|
[CGI.escape("#{k}[]"), CGI.escape(vv.to_s)].join("=")
}
else
[CGI.escape(k.to_s), CGI.escape(v.to_s)].join("=")
end
}.flatten.join("&")
end
end

0 comments on commit da312e7

Please sign in to comment.