forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
56 lines (45 loc) · 1.18 KB
/
decoder.go
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
package mediaheader
import (
"github.com/github/hub/Godeps/_workspace/src/github.com/jingweno/go-sawyer/hypermedia"
"net/http"
"net/url"
"strings"
)
// TODO: need a full link header parser for http://tools.ietf.org/html/rfc5988
type Decoder struct {
}
func (d *Decoder) Decode(header http.Header) (mediaHeader *MediaHeader) {
mediaHeader = &MediaHeader{Relations: hypermedia.Relations{}}
link := header.Get("Link")
if len(link) == 0 {
return
}
for _, l := range strings.Split(link, ",") {
l = strings.TrimSpace(l)
segments := strings.Split(l, ";")
if len(segments) < 2 {
continue
}
if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") {
continue
}
url, err := url.Parse(segments[0][1 : len(segments[0])-1])
if err != nil {
continue
}
link := hypermedia.Hyperlink(url.String())
for _, segment := range segments[1:] {
switch strings.TrimSpace(segment) {
case `rel="next"`:
mediaHeader.Relations["next"] = link
case `rel="prev"`:
mediaHeader.Relations["prev"] = link
case `rel="first"`:
mediaHeader.Relations["first"] = link
case `rel="last"`:
mediaHeader.Relations["last"] = link
}
}
}
return
}