Last active
May 13, 2022 20:26
-
-
Save eduardoazevedo3/70f0bf4a258e5e8b4e3c78bd84be381d to your computer and use it in GitHub Desktop.
Workaround for Ruby incompatibility with TLS 1.3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Curl | |
| attr_accessor :response, :res, :params | |
| def self.request(*args, &block) | |
| new(*args, &block).request | |
| end | |
| def initialize(params = {}) | |
| @response = OpenStruct.new headers: {}, body: '' | |
| @params = params | |
| @res = '' | |
| end | |
| def request | |
| return unless valid? | |
| @res = execute | |
| prepare_response | |
| end | |
| private | |
| def execute | |
| `curl -X #{params[:method].upcase} #{params[:url]} -s -i \ | |
| #{prepare_headers} \ | |
| #{prepare_payload}` | |
| end | |
| def prepare_headers | |
| return if params[:headers].blank? | |
| params[:headers] | |
| .map { |k, v| "-H \"#{k}: #{v}\"" } | |
| .join(" ") | |
| end | |
| def prepare_payload | |
| return if params[:payload].blank? | |
| if params[:payload].is_a?(Hash) | |
| params[:payload] | |
| .map { |k, v| "-d \"#{k}=#{v}\"" } | |
| .join(" ") | |
| elsif params[:payload].is_a?(String) | |
| "-d #{params[:payload]}" | |
| end | |
| end | |
| def prepare_response | |
| res_array = res.split("\r\n") | |
| header_area = false | |
| body_area = false | |
| res_array.each_with_index do |item, i| | |
| header_area = i.positive? && !body_area && item.present? | |
| header_attr = item.squish.split(':') if header_area | |
| response.status = item.split.last.to_i if i.zero? | |
| response.headers.merge!({ header_attr.first.squish => header_attr.last.squish }) if header_area | |
| response.body << item if body_area | |
| body_area = !body_area ? i.positive? && item.blank? : true | |
| end | |
| response | |
| end | |
| def valid? | |
| raise 'Invalid http verb' unless %w[get post put patch delete].include?(params[:method].to_s.downcase) | |
| raise 'Invalid url' unless URI.parse(params[:url].to_s).host | |
| true | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| response = Curl.request( | |
| method: 'post', | |
| payload: { username: 'Bret' }, | |
| url: 'https://jsonplaceholder.typicode.com/users', | |
| headers: { | |
| content_type: 'application/x-www-form-urlencoded', | |
| authorization: 'Bearer f36a62b465...' | |
| } | |
| ) | |
| p response.status | |
| p response.headers | |
| p response.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment