module Async2::HTTP
Constants
- BUFF_LEN
Public Instance Methods
get(uri, headers = {}) { |body, res, buff| ... }
click to toggle source
# File lib/async2/http.rb, line 35 def get(uri, headers = {}) request(uri, "GET", headers) do |body, res, buff| yield body, res, buff end end
request(uri, verb = "GET", headers = {}, body = nil) { |body, rep, buff| ... }
click to toggle source
# File lib/async2/http.rb, line 41 def request(uri, verb = "GET", headers = {}, body = nil) uri = URI.parse uri uri.path = "/" if uri.path == "" headers["User-Agent"] = "ruby/#{RUBY_VERSION}" headers["Host"] = uri.hostname headers["Accept"] = "*/*" buffer = "#{verb} #{uri.path} HTTP/1.1\r\n" + headers.map { |k, v| "#{k}: #{v}" }.join("\r\n") + "\r\n\r\n" buffer += "\r\n#{body}" if body socket = TCPSocket.new uri.hostname, uri.port p "client> #{buffer}" socket.print buffer Async2.instance.read(socket) do buff = read_all(socket) rep, body = to_response(buff, socket) yield body, rep, buff end end
Private Instance Methods
read_all(io)
click to toggle source
# File lib/async2/http.rb, line 10 def read_all(io) buff = "" while (l = io.read_nonblock BUFF_LEN) buff += l break if l.size < BUFF_LEN end buff end
to_response(buff, io = nil)
click to toggle source
# File lib/async2/http.rb, line 19 def to_response(buff, io = nil) split = buff.split("\r\n") first = split.first rep = Net::HTTPResponse.new first.split[0], Integer(first.split[1]), first.split[2] rep.instance_variable_set "@socket", io idx = split.index "" if idx headers = split[1 .. (idx - 1)] body = split[idx .. -1].join if idx < split.size - 1 headers.each { |e| head = e.match(/([^:]+): (.+)/) ; rep[head[1]] = head[2] } rep.body = body return [rep, body] end return [rep, nil] end