blob: d98c237baf3bbc64a95d01bd4e13847bd16d216b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
|
# frozen_string_literal: true
module Gitlab
module Utils
# Parses Link http headers (as defined in https://www.rfc-editor.org/rfc/rfc5988.txt)
#
# The URI-references with their relation type are extracted and returned as a hash
# Example:
#
# header = '<http://test.org/TheBook/chapter2>; rel="previous", <http://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>
# }
# }
class LinkHeaderParser
REL_PATTERN = %r{rel="(\w+)"}.freeze
# to avoid parse really long URIs we limit the amount of characters allowed
URI_PATTERN = %r{<(.{1,500})>}.freeze
def initialize(header)
@header = header
end
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
end
end
end
|