Adds String method for Links

This commit is contained in:
Tom Hudson 2016-06-17 00:32:30 +01:00
parent 9700717000
commit 2d1ed05a44
3 changed files with 39 additions and 2 deletions

View File

@ -61,3 +61,16 @@ func ExampleLink_String() {
// Output: // Output:
// Link: <http://example.com/page/2>; rel="next" // Link: <http://example.com/page/2>; rel="next"
} }
func ExampleLinks_String() {
links := linkheader.Links{
{URL: "http://example.com/page/3", Rel: "next"},
{URL: "http://example.com/page/1", Rel: "last"},
}
fmt.Printf("Link: %s\n", links.String())
// Output:
// Link: <http://example.com/page/3>; rel="next", <http://example.com/page/1>; rel="last"
}

13
main.go
View File

@ -33,8 +33,7 @@ func (l Link) Param(key string) (string, error) {
return "", fmt.Errorf("Could not find param '%s'", key) return "", fmt.Errorf("Could not find param '%s'", key)
} }
// String returns the string representation of a Link header // String returns the string representation of a link
// for use in HTTP responses
func (l Link) String() string { func (l Link) String() string {
p := make([]string, len(l.Params)) p := make([]string, len(l.Params))
@ -61,6 +60,16 @@ func (l Links) FilterByRel(r string) Links {
return links return links
} }
// String returns the string representation of multiple Links
// for use in HTTP responses etc
func (l Links) String() string {
strs := make([]string, 0)
for _, link := range l {
strs = append(strs, link.String())
}
return strings.Join(strs, ", ")
}
// Parse parses a raw Link header in the form: // Parse parses a raw Link header in the form:
// <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

View File

@ -131,3 +131,18 @@ func TestLinkToString(t *testing.T) {
t.Errorf("Re-parsed link header should have matching rel, but has `%s`", parsed[0].Rel) t.Errorf("Re-parsed link header should have matching rel, but has `%s`", parsed[0].Rel)
} }
} }
func TestLinksToString(t *testing.T) {
ls := Links{
{URL: "http://example.com/page/3", Rel: "next"},
{URL: "http://example.com/page/1", Rel: "last"},
}
have := ls.String()
want := "<http://example.com/page/3>; rel=\"next\", <http://example.com/page/1>; rel=\"last\""
if have != want {
t.Errorf("Want `%s`, have `%s`", want, have)
}
}