Merge pull request #2 from 178inaba/empty_parse

Fix to return nil if parse empty string
This commit is contained in:
Tom Hudson 2017-05-04 10:57:20 +01:00 committed by GitHub
commit ee06f2596c
4 changed files with 31 additions and 12 deletions

View File

@ -1,14 +1,6 @@
language: go language: go
go: go:
- 1.5
- 1.6 - 1.6
- 1.7
- tip - tip
install:
- ./script/bootstrap
script:
- ./script/test
# - ./script/lint

View File

@ -1,6 +1,6 @@
# Golang Link Header Parser # Golang Link Header Parser
Library for parsing HTTP Link headers. Requires Go 1.2 or higher. Library for parsing HTTP Link headers. Requires Go 1.6 or higher.
Docs can be found on [the GoDoc page](https://godoc.org/github.com/tomnomnom/linkheader). Docs can be found on [the GoDoc page](https://godoc.org/github.com/tomnomnom/linkheader).

View File

@ -63,6 +63,10 @@ func (l Links) FilterByRel(r string) Links {
// String returns the string representation of multiple Links // String returns the string representation of multiple Links
// for use in HTTP responses etc // for use in HTTP responses etc
func (l Links) String() string { func (l Links) String() string {
if l == nil {
return fmt.Sprint(nil)
}
var strs []string var strs []string
for _, link := range l { for _, link := range l {
strs = append(strs, link.String()) strs = append(strs, link.String())
@ -74,7 +78,7 @@ func (l Links) String() string {
// <url>; rel="foo", <url>; rel="bar"; wat="dis" // <url>; rel="foo", <url>; rel="bar"; wat="dis"
// returning a slice of Link structs // returning a slice of Link structs
func Parse(raw string) Links { func Parse(raw string) Links {
links := make(Links, 0) var links Links
// One chunk: <url>; rel="foo" // One chunk: <url>; rel="foo"
for _, chunk := range strings.Split(raw, ",") { for _, chunk := range strings.Split(raw, ",") {
@ -110,8 +114,10 @@ func Parse(raw string) Links {
} }
if link.URL != "" {
links = append(links, link) links = append(links, link)
} }
}
return links return links
} }

View File

@ -38,6 +38,27 @@ func TestSimple(t *testing.T) {
} }
func TestEmpty(t *testing.T) {
links := Parse("")
if links != nil {
t.Errorf("Return value should be nil, but was %s", len(links))
}
}
// Although not often seen in the wild, the grammar in RFC 5988 suggests that it's
// valid for a link header to have nothing but a URL.
func TestNoRel(t *testing.T) {
links := Parse("<http://example.com>")
if len(links) != 1 {
t.Fatalf("Length of links should be 1, but was %d", len(links))
}
if links[0].URL != "http://example.com" {
t.Errorf("URL should be http://example.com, but was %s", links[0].URL)
}
}
func TestLinkMethods(t *testing.T) { func TestLinkMethods(t *testing.T) {
header := "<https://api.github.com/user/9287/repos?page=1&per_page=100>; rel=\"prev\"; pet=\"cat\"" header := "<https://api.github.com/user/9287/repos?page=1&per_page=100>; rel=\"prev\"; pet=\"cat\""
links := Parse(header) links := Parse(header)