Sha256: b6f7e0b0e68044d463c4aa1837f42862eb34a14bbd9ed59ba969f5b392453e59

Contents?: true

Size: 1.46 KB

Versions: 7

Compression:

Stored size: 1.46 KB

Contents

require 'net/http'
require 'open-uri'
require 'yajl/json_gem'
require 'kurchatov/version'

module Kurchatov
  module Mixin
    module Http

      USER_AGENT = "Kurchatov (Riemann client)".freeze

      # /path/to/file, https://ya.ru, http://a:a@yandex.ru
      def rest_get(url)
        uri = URI(url)
        if uri.userinfo
          open("#{uri.scheme}://#{uri.hostname}:#{uri.port}#{uri.request_uri}",
               :http_basic_authentication => [uri.user, uri.password],
               'User-Agent' => USER_AGENT).read
        else
          open(url, 'User-Agent' => USER_AGENT).read
        end
      end

      # return: body, http_code
      def http_get(url)
        uri = URI(url)
        req = Net::HTTP::Get.new(uri)
        req['User-Agent'] = USER_AGENT
        res = nil
        begin
          Net::HTTP.start(uri.hostname, uri.port) {|http| res = http.request(req)}
        rescue SocketError, Errno::ECONNREFUSED
          return nil, 0
        end
        return res.body, res.code.to_i
      end

      # return: body, http_code
      def http_post(url, body)
        uri = URI(url)
        http = Net::HTTP.new(uri.host, uri.port)
        path = uri.path == '' ? '/' : uri.path
        request = Net::HTTP::Post.new(path)
        request.body = body
        begin
          response = http.request(request)
        rescue SocketError, Errno::ECONNREFUSED
          return nil, 0
        end
        return response.body, response.code.to_i
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
kurchatov-0.4.7 lib/kurchatov/mixin/http.rb
kurchatov-0.4.6 lib/kurchatov/mixin/http.rb
kurchatov-0.4.5 lib/kurchatov/mixin/http.rb
kurchatov-0.4.4 lib/kurchatov/mixin/http.rb
kurchatov-0.4.3 lib/kurchatov/mixin/http.rb
kurchatov-0.4.2 lib/kurchatov/mixin/http.rb
kurchatov-0.4.1 lib/kurchatov/mixin/http.rb