Class: Gitlab::Utils::LinkHeaderParser

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

Overview

Parses Link http headers (as defined in www.rfc-editor.org/rfc/rfc5988.txt)

The URI-references with their relation type are extracted and returned as a hash Example:

header = ‘<test.org/TheBook/chapter2>; rel=“previous”, <test.org/TheBook/chapter4>; rel=“next”’

Gitlab::Utils::LinkHeaderParser.new(header).parse {

previous: {
  uri: #<URI::HTTP http://test.org/TheBook/chapter2>
},
next: {
  uri: #<URI::HTTP http://test.org/TheBook/chapter4>
}

}

Constant Summary collapse

REL_PATTERN =
%r{rel="(\w+)"}
URI_PATTERN =

to avoid parse really long URIs we limit the amount of characters allowed

%r{<(.{1,500})>}

Instance Method Summary collapse

Constructor Details

#initialize(header) ⇒ LinkHeaderParser

Returns a new instance of LinkHeaderParser.



26
27
28
# File 'lib/gitlab/utils/link_header_parser.rb', line 26

def initialize(header)
  @header = header
end

Instance Method Details

#parseObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gitlab/utils/link_header_parser.rb', line 30

def parse
  return {} if @header.blank?

  links = @header.split(',')
  result = {}
  links.each do |link|
    direction = link[REL_PATTERN, 1]&.to_sym
    uri = link[URI_PATTERN, 1]

    result[direction] = { uri: URI(uri) } if direction && uri
  end

  result
end