File: link.go

package info (click to toggle)
golang-github-tent-http-link-go 0.0~git20130702.0.ac974c6-2~bpo8+1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 76 kB
  • sloc: makefile: 3
file content (185 lines) | stat: -rw-r--r-- 3,978 bytes parent folder | download | duplicates (3)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Package link implements parsing and serialization of Link header values as
// defined in RFC 5988.
package link

import (
	"bytes"
	"errors"
	"sort"
	"unicode"
)

type Link struct {
	URI    string
	Rel    string
	Params map[string]string
}

// Format serializes a slice of Links into a header value. It does not currently
// implement RFC 2231 handling of non-ASCII character encoding and language
// information.
func Format(links []Link) string {
	buf := &bytes.Buffer{}
	for i, link := range links {
		if i > 0 {
			buf.Write([]byte(", "))
		}
		buf.WriteByte('<')
		buf.WriteString(link.URI)
		buf.WriteByte('>')

		writeParam(buf, "rel", link.Rel)

		keys := make([]string, 0, len(link.Params))
		for k := range link.Params {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		for _, k := range keys {
			writeParam(buf, k, link.Params[k])
		}
	}

	return buf.String()
}

func writeParam(buf *bytes.Buffer, key, value string) {
	buf.Write([]byte("; "))
	buf.WriteString(key)
	buf.Write([]byte(`="`))
	buf.WriteString(value)
	buf.WriteByte('"')
}

// Parse parses a Link header value into a slice of Links. It does not currently
// implement RFC 2231 handling of non-ASCII character encoding and language
// information.
func Parse(l string) ([]Link, error) {
	v := []byte(l)
	v = bytes.TrimSpace(v)
	if len(v) == 0 {
		return nil, nil
	}

	links := make([]Link, 0, 1)
	for len(v) > 0 {
		if v[0] != '<' {
			return nil, errors.New("link: does not start with <")
		}
		lend := bytes.IndexByte(v, '>')
		if lend == -1 {
			return nil, errors.New("link: does not contain ending >")
		}

		params := make(map[string]string)
		link := Link{URI: string(v[1:lend]), Params: params}
		links = append(links, link)

		// trim off parsed url
		v = v[lend+1:]
		if len(v) == 0 {
			break
		}
		v = bytes.TrimLeftFunc(v, unicode.IsSpace)

		for len(v) > 0 {
			if v[0] != ';' && v[0] != ',' {
				return nil, errors.New(`link: expected ";" or "'", got "` + string(v[0:1]) + `"`)
			}
			var next bool
			if v[0] == ',' {
				next = true
			}
			v = bytes.TrimLeftFunc(v[1:], unicode.IsSpace)
			if next || len(v) == 0 {
				break
			}
			var key, value []byte
			key, value, v = consumeParam(v)
			if key == nil || value == nil {
				return nil, errors.New("link: malformed param")
			}
			if k := string(key); k == "rel" {
				if links[len(links)-1].Rel == "" {
					links[len(links)-1].Rel = string(value)
				}
			} else {
				params[k] = string(value)
			}
			v = bytes.TrimLeftFunc(v, unicode.IsSpace)
		}
	}

	return links, nil
}

func isTokenChar(r rune) bool {
	return r > 0x20 && r < 0x7f && r != '"' && r != ',' && r != '=' && r != ';'
}

func isNotTokenChar(r rune) bool { return !isTokenChar(r) }

func consumeToken(v []byte) (token, rest []byte) {
	notPos := bytes.IndexFunc(v, isNotTokenChar)
	if notPos == -1 {
		return v, nil
	}
	if notPos == 0 {
		return nil, v
	}
	return v[0:notPos], v[notPos:]
}

func consumeValue(v []byte) (value, rest []byte) {
	if v[0] != '"' {
		return nil, v
	}

	rest = v[1:]
	buffer := &bytes.Buffer{}
	var nextIsLiteral bool
	for idx, r := range string(rest) {
		switch {
		case nextIsLiteral:
			buffer.WriteRune(r)
			nextIsLiteral = false
		case r == '"':
			return buffer.Bytes(), rest[idx+1:]
		case r == '\\':
			nextIsLiteral = true
		case r != '\r' && r != '\n':
			buffer.WriteRune(r)
		default:
			return nil, v
		}
	}
	return nil, v
}

func consumeParam(v []byte) (param, value, rest []byte) {
	param, rest = consumeToken(v)
	param = bytes.ToLower(param)
	if param == nil {
		return nil, nil, v
	}

	rest = bytes.TrimLeftFunc(rest, unicode.IsSpace)
	if len(rest) == 0 || rest[0] != '=' {
		return nil, nil, v
	}
	rest = rest[1:] // consume equals sign
	rest = bytes.TrimLeftFunc(rest, unicode.IsSpace)
	if len(rest) == 0 {
		return nil, nil, v
	}
	if rest[0] != '"' {
		value, rest = consumeToken(rest)
	} else {
		value, rest = consumeValue(rest)
	}
	if value == nil {
		return nil, nil, v
	}
	return param, value, rest
}