Module: Async2::HTTP

Included in:
Async2
Defined in:
lib/async2/http.rb

Constant Summary collapse

BUFF_LEN =
4096

Instance Method Summary collapse

Instance Method Details

#get(uri, headers = {}) ⇒ Object



35
36
37
38
39
# 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) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 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