Class: Net::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/em-net-http.rb

Instance Method Summary collapse

Instance Method Details

#do_startObject



107
108
109
110
111
112
# File 'lib/em-net-http.rb', line 107

def do_start

  return orig_net_http_do_start unless ::EM.reactor_running?

  @started = true
end

#orig_net_http_do_startObject



105
# File 'lib/em-net-http.rb', line 105

alias_method :orig_net_http_do_start, :do_start

#orig_net_http_requestObject



103
# File 'lib/em-net-http.rb', line 103

alias_method :orig_net_http_request, :request

#request(req, body = nil, &block) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/em-net-http.rb', line 114

def request(req, body = nil, &block)

  return orig_net_http_request(req, body, &block) unless ::EM.reactor_running?

  uri = Addressable::URI.parse("#{use_ssl? ? 'https://' : 'http://'}#{addr_port}#{req.path}")

  body = body || req.body
  opts = body.nil? ? {} : {:body => body}
  if use_ssl?
    sslopts = opts[:ssl] = {}
    sslopts[:verify_peer] = verify_mode == OpenSSL::SSL::VERIFY_PEER
    sslopts[:private_key_file] = key if key
    sslopts[:cert_chain_file] = ca_file if ca_file
  end
  opts[:timeout] = self.read_timeout

  headers = opts[:head] = {}
  req.each do |k, v|
    headers[k] = v
  end

  headers['content-type'] ||= "application/x-www-form-urlencoded"

  t0 = Time.now
  httpreq = EM::HttpRequest.new(uri).send(req.class::METHOD.downcase.to_sym, opts)

  f=Fiber.current

  convert_em_http_response = lambda do |res|
    emres = EM::NetHTTP::Response.new(res.response_header)
    emres.set_body res.response
    nhresclass = Net::HTTPResponse.response_class(emres.code)
    nhres = nhresclass.new(emres.http_version, emres.code, emres.message)
    emres.to_hash.each do |k, v|
      nhres.add_field(k, v)
    end
    nhres.body = emres.body if req.response_body_permitted? && nhresclass.body_permitted?
    nhres.instance_variable_set '@read', true
    f.resume nhres
  end


  if block_given?
    httpreq.headers { |headers|

      emres = EM::NetHTTP::Response.new(headers)
      nhresclass = Net::HTTPResponse.response_class(emres.code)
      nhres = nhresclass.new(emres.http_version, emres.code, emres.message)
      emres.to_hash.each do |k, v|
        nhres.add_field(k, v)
      end
      f.resume nhres
    }
    httpreq.errback {|err|f.resume(err)}

    nhres = yield_with_error_check(t0)
    nhres.instance_variable_set :@httpreq, httpreq

    yield nhres
    nhres
  else
    httpreq.callback &convert_em_http_response
    httpreq.errback {|err|f.resume(err)}

    yield_with_error_check(t0)
  end
end