lib/hatetepe/client.rb in hatetepe-0.4.0 vs lib/hatetepe/client.rb in hatetepe-0.4.1
- old
+ new
@@ -74,10 +74,12 @@
pending_response[req.object_id].succeed response
end
end
def <<(request)
+ request.headers["Host"] ||= "#{config[:host]}:#{config[:port]}"
+
request.connection = self
unless processing_enabled?
request.fail
return
end
@@ -99,22 +101,21 @@
end
end.resume
end
def request(verb, uri, headers = {}, body = nil, http_version = "1.1")
- headers["Host"] ||= "#{config[:host]}:#{config[:port]}"
headers["User-Agent"] ||= "hatetepe/#{Hatetepe::VERSION}"
body = wrap_body(body)
- if headers["Content-Type"] == "application/x-www-form-urlencoded"
- enum = Enumerator.new(body)
- headers["Content-Length"] = enum.inject(0) {|a, e| a + e.length }
- end
+ headers, body = encode_body(headers.dup, body)
request = Hatetepe::Request.new(verb, uri, headers, body, http_version)
self << request
+
+ # XXX shouldn't this happen in ::request ?
self.processing_enabled = false
+
EM::Synchrony.sync request
request.response.body.close_write if request.verb == "HEAD"
request.response
@@ -157,9 +158,40 @@
elsif body
[body]
else
[]
end
+ end
+
+ def encode_body(headers, body)
+ multipart, urlencoded = false, false
+ if Hash === body
+ query = lambda do |value|
+ case value
+ when Array
+ value.each &query
+ when Hash
+ value.values.each &query
+ when Rack::Multipart::UploadedFile
+ multipart = true
+ end
+ end
+ body.values.each &query
+ urlencoded = !multipart
+ end
+
+ body = if multipart
+ boundary = Rack::Multipart::MULTIPART_BOUNDARY
+ headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
+ [Rack::Multipart.build_multipart(body)]
+ elsif urlencoded
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ [Rack::Utils.build_nested_query(body)]
+ else
+ body
+ end
+
+ [headers, body]
end
class << self
def start(config)
EM.connect config[:host], config[:port], self, config