Encode Spaces in Query Strings as '%20' Instead of '+' (#1125)

This commit is contained in:
Karl Entwistle 2020-03-29 11:48:15 +01:00 committed by GitHub
parent b4ad6e386e
commit 864a7e52f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 1 deletions

View File

@ -16,12 +16,20 @@ module Faraday
NestedParamsEncoder.encode(params)
end
def default_space_encoding
@default_space_encoding ||= '+'
end
class << self
attr_writer :default_space_encoding
end
ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/.freeze
def escape(str)
str.to_s.gsub(ESCAPE_RE) do |match|
'%' + match.unpack('H2' * match.bytesize).join('%').upcase
end.tr(' ', '+')
end.gsub(' ', default_space_encoding)
end
def unescape(str)

View File

@ -67,4 +67,17 @@ RSpec.describe Faraday::Request::UrlEncoded do
response = conn.post('/echo', 'a' => { 'b' => { 'c' => ['d'] } })
expect(response.body).to eq('a%5Bb%5D%5Bc%5D%5B%5D=d')
end
context 'customising default_space_encoding' do
around do |example|
Faraday::Utils.default_space_encoding = '%20'
example.run
Faraday::Utils.default_space_encoding = nil
end
it 'uses the custom character to encode spaces' do
response = conn.post('/echo', str: 'apple banana')
expect(response.body).to eq('str=apple%20banana')
end
end
end