Class: Webtube::Request

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

Overview

Represents an HTTP request (well, request header, since a WebSocket open request shouldn’t have a body) being prepared to open a WebSocket connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(location, custom_fields = {}) ⇒ Request

Returns a new instance of Request.



556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/webtube.rb', line 556

def initialize location, custom_fields = {}
  super()
  @location = location
  @fields = {} # capitalised-name => value
  # Since Ruby hashes are case-sensitive but HTTP header
  # field names are case-insensitive, we may have to combine
  # fields whose names only differ in case.
  custom_fields.each_pair do |name, value|
    name = name.capitalize
    if @fields.has_key? name then
      @fields[name] += ', ' + value
    else
      @fields[name] = value
    end
  end

  # Add in the WebSocket header fields but give precedence
  # to user-specified values
  @fields['Host'] ||= @location.host_and_maybe_port
  @fields['Upgrade'] ||= 'websocket'
  @fields['Connection'] ||= 'upgrade'
  @fields['Sec-websocket-key'] ||=
      SecureRandom.base64(16)
  @fields['Sec-websocket-version'] ||= '13'

  return
end

Instance Attribute Details

#locationObject (readonly)

Returns the value of attribute location.



554
555
556
# File 'lib/webtube.rb', line 554

def location
  @location
end

Instance Method Details

#[](name) ⇒ Object



584
585
586
# File 'lib/webtube.rb', line 584

def [] name
  return @fields[name.capitalize]
end

#[]=(name, value) ⇒ Object



588
589
590
591
592
593
594
595
596
# File 'lib/webtube.rb', line 588

def []= name, value
  name = name.capitalize
  unless value.nil? then
    @fields[name] = value
  else
    @fields.delete name
  end
  return value
end

#each_pair(&thunk) ⇒ Object



598
599
600
601
# File 'lib/webtube.rb', line 598

def each_pair &thunk
  @fields.each_pair &thunk
  return self
end

#expected_acceptObject



616
617
618
619
620
# File 'lib/webtube.rb', line 616

def expected_accept
  return OpenSSL::Digest::SHA1.base64digest(
      self['Sec-WebSocket-Key'] +
      '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
end

#to_sObject

Constructs an HTTP request header in string form, together with CRLF line terminators and the terminal blank line, ready to be transmitted to the server.



606
607
608
609
610
611
612
613
614
# File 'lib/webtube.rb', line 606

def to_s
  s = ''
  s << "GET #{@location.requestee} HTTP/1.1\r\n"
  each_pair do |k, v|
    s << "#{k}: #{v}\r\n"
  end
  s << "\r\n"
  return s
end