Class: Biryani::HTTP::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/biryani/http/response.rb

Constant Summary collapse

FORBIDDEN_KEY_CHARS =
(0x00..0x20).chain([0x3a]).chain(0x41..0x5a).chain(0x7f..0xff).to_a.freeze
FORBIDDEN_VALUE_CHARS =
[0x00, 0x0a, 0x0d].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status, fields, content) ⇒ Response

Returns a new instance of Response.

Parameters:

  • status (Integer)
  • fields (Hash)
  • content (String, nil)


12
13
14
15
16
# File 'lib/biryani/http/response.rb', line 12

def initialize(status, fields, content)
  @status = status
  @fields = fields
  @content = content
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



7
8
9
# File 'lib/biryani/http/response.rb', line 7

def content
  @content
end

#fieldsObject

Returns the value of attribute fields.



7
8
9
# File 'lib/biryani/http/response.rb', line 7

def fields
  @fields
end

#statusObject

Returns the value of attribute status.



7
8
9
# File 'lib/biryani/http/response.rb', line 7

def status
  @status
end

Class Method Details

.defaultObject

rubocop: enable Metrics/CyclomaticComplexity



29
30
31
# File 'lib/biryani/http/response.rb', line 29

def self.default
  Response.new(0, {}, nil)
end

.internal_server_errorObject



33
34
35
# File 'lib/biryani/http/response.rb', line 33

def self.internal_server_error
  Response.new(500, {}, 'Internal Server Error')
end

Instance Method Details

#validateObject

rubocop: disable Metrics/CyclomaticComplexity

Raises:

  • (InvalidHTTPResponseError)


20
21
22
23
24
25
26
# File 'lib/biryani/http/response.rb', line 20

def validate
  # https://datatracker.ietf.org/doc/html/rfc9113#section-8.2.1
  raise Error::InvalidHTTPResponseError, 'invalid HTTP status' if @status < 100 || @status >= 600
  raise Error::InvalidHTTPResponseError, 'HTTP field name contains invalid characters' if (@fields.keys.join.downcase.bytes.uniq & FORBIDDEN_KEY_CHARS).any?
  raise Error::InvalidHTTPResponseError, 'HTTP field value contains NUL, LF or CR' if (@fields.values.join.bytes.uniq & FORBIDDEN_VALUE_CHARS).any?
  raise Error::InvalidHTTPResponseError, 'HTTP field value starts/ends with SP or HTAB' if @fields.values.filter { |s| s.start_with?("\t", ' ') || s.end_with?("\t", ' ') }.any?
end