Class: MKIt::HttpClient
- Inherits:
-
Object
- Object
- MKIt::HttpClient
- Defined in:
- lib/mkit/client/http_client.rb
Instance Method Summary collapse
- #attach(file) ⇒ Object
-
#client(req) ⇒ Object
http client.
-
#initialize(server_url, my_id) ⇒ HttpClient
constructor
A new instance of HttpClient.
- #request(request, request_data = {}) ⇒ Object
Constructor Details
#initialize(server_url, my_id) ⇒ HttpClient
Returns a new instance of HttpClient.
14 15 16 17 |
# File 'lib/mkit/client/http_client.rb', line 14 def initialize(server_url, my_id) @server_url = server_url @my_id = my_id end |
Instance Method Details
#attach(file) ⇒ Object
79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/mkit/client/http_client.rb', line 79 def attach(file) boundary = SecureRandom.alphanumeric body = [] body << "--#{boundary}\r\n" body << "Content-Disposition: form-data; name=file; filename='#{File.basename(file)}'\r\n" body << "Content-Type: text/plain\r\n" body << "\r\n" body << File.read(file) body << "\r\n--#{boundary}--\r\n" [body.join, boundary] end |
#client(req) ⇒ Object
http client
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/mkit/client/http_client.rb', line 23 def client(req) req['X-API-KEY'] = @my_id uri = URI(@server_url) case uri.scheme when 'https' @client = NetX::HTTPUnix.new(uri.host, uri.port) @client.use_ssl = true @client.verify_mode = OpenSSL::SSL::VERIFY_NONE when 'http' @client = NetX::HTTPUnix.new(uri.host, uri.port) when 'sock' @client = NetX::HTTPUnix.new("unix://#{uri.path}") else raise InvalidParametersException, 'Invalid mkit server uri. Please check configuration' end @client.request(req) end |
#request(request, request_data = {}) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/mkit/client/http_client.rb', line 41 def request(request, request_data = {}) req = nil uri = request[:uri] request[:file] = request_data[:file] unless request[:params].nil? || request[:params].empty? uri = uri + '?' + request[:params].map { |k| "#{k}=#{request_data[k]}" }.join('&') end uri = ERB.new(uri).result_with_hash(request_data) # puts "Request URI: #{uri}" case request[:verb].to_sym when :post req = Net::HTTP::Post.new(uri) unless request[:file].nil? (body, boundary) = attach(request[:file]) req.body = body req['Content-Type'] = "multipart/form-data, boundary=#{boundary}" end when :put req = Net::HTTP::Put.new(uri) unless request[:file].nil? (body, boundary) = attach(request[:file]) req.body = body req['Content-Type'] = "multipart/form-data, boundary=#{boundary}" end when :patch req = Net::HTTP::Patch.new(uri) when :get req = Net::HTTP::Get.new(uri) when :delete req = Net::HTTP::Delete.new(uri) when :ws end client(req).body end |