module Coolio::HttpEncoding

Methods for building HTTP requests

Constants

FIELD_ENCODING
HTTP_REQUEST_HEADER

Public Instance Methods

encode_cookies(cookies) click to toggle source
# File lib/cool.io/http_client.rb, line 109
def encode_cookies(cookies)
  cookies.inject('') { |result, (k, v)| result << encode_field('Cookie', encode_param(k, v)) }
end
encode_field(k, v) click to toggle source

Encode a field in an HTTP header

# File lib/cool.io/http_client.rb, line 97
def encode_field(k, v)
  FIELD_ENCODING % [k, v]
end
encode_headers(head) click to toggle source
# File lib/cool.io/http_client.rb, line 101
def encode_headers(head)
  head.inject('') do |result, (key, value)|
    # Munge keys from foo-bar-baz to Foo-Bar-Baz
    key = key.split('-').map { |k| k.capitalize }.join('-')
  result << encode_field(key, value)
  end
end
encode_host() click to toggle source

HTTP is kind of retarded that you have to specify a Host header, but if you include port 80 then further redirects will tack on the :80 which is annoying.

# File lib/cool.io/http_client.rb, line 78
def encode_host
  remote_host + (remote_port.to_i != 80 ? ":#{remote_port}" : "")
end
encode_param(k, v) click to toggle source

URL encodes a single k=v parameter.

# File lib/cool.io/http_client.rb, line 92
def encode_param(k, v)
  escape(k) + "=" + escape(v)
end
encode_query(path, query) click to toggle source
# File lib/cool.io/http_client.rb, line 86
def encode_query(path, query)
  return path unless query
  path + "?" + query.map { |k, v| encode_param(k, v) }.join('&')
end
encode_request(method, path, query) click to toggle source
# File lib/cool.io/http_client.rb, line 82
def encode_request(method, path, query)
  HTTP_REQUEST_HEADER % [method.to_s.upcase, encode_query(path, query)]
end
escape(s) click to toggle source

Escapes a URI.

# File lib/cool.io/http_client.rb, line 57
def escape(s)
  s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
    '%'+$1.unpack('H2'*$1.size).join('%').upcase
  }.tr(' ', '+')
end
munge_header_keys(head) click to toggle source

Map all header keys to a downcased string version

# File lib/cool.io/http_client.rb, line 71
def munge_header_keys(head)
  head.inject({}) { |h, (k, v)| h[k.to_s.downcase] = v; h }
end
unescape(s) click to toggle source

Unescapes a URI escaped string.

# File lib/cool.io/http_client.rb, line 64
def unescape(s)
  s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
    [$1.delete('%')].pack('H*')
  }
end