Class: Http2::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/http2/utils.rb

Overview

This class holds various methods for encoding, decoding and parsing of HTTP-related stuff.

Class Method Summary collapse

Class Method Details

.parse_set_cookies(str) ⇒ Object

Parses a cookies-string and returns them in an array.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/http2/utils.rb', line 20

def self.parse_set_cookies(str)
  str = str.to_s
  return [] if str.empty?

  cookie_start_regex = /^(.+?)=(.*?)(;\s*|$)/

  match = str.match(cookie_start_regex)
  raise "Could not match cookie: '#{str}'" unless match

  str.gsub!(cookie_start_regex, "")

  cookie_data = {
    name: urldec(match[1].to_s),
    value: urldec(match[2].to_s)
  }

  while (match = str.match(/(.+?)=(.*?)(;\s*|$)/))
    str = str.gsub(match[0], "")
    key = match[1].to_s.downcase
    value = match[2].to_s

    if key == "path" || key == "expires"
      cookie_data[key.to_sym] = value
    else
      cookie_data[key] = value
    end
  end

  cookie = Http2::Cookie.new(cookie_data)

  [cookie]
end

.urldec(string) ⇒ Object

URL-decodes a string.



12
13
14
15
16
17
# File 'lib/http2/utils.rb', line 12

def self.urldec(string)
  # Thanks to CGI framework
  string.to_s.tr("+", " ").gsub(/((?:%[0-9a-fA-F]{2})+)/) do
    [Regexp.last_match(1).delete("%")].pack("H*")
  end
end

.urlenc(string) ⇒ Object

URL-encodes a string.



4
5
6
7
8
9
# File 'lib/http2/utils.rb', line 4

def self.urlenc(string)
  # Thanks to CGI framework
  string.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/) do
    "%#{Regexp.last_match(1).unpack("H2" * Regexp.last_match(1).bytesize).join("%").upcase}"
  end.tr(" ", "+")
end