diff --git a/main.go b/main.go index 118b631..a86f2ed 100644 --- a/main.go +++ b/main.go @@ -33,6 +33,20 @@ func (l Link) Param(key string) (string, error) { return "", fmt.Errorf("Could not find param '%s'", key) } +// String returns the string representation of a Link header +// for use in HTTP responses +func (l Link) String() string { + + p := make([]string, len(l.Params)) + for k, v := range l.Params { + p = append(p, fmt.Sprintf("%s=\"%s\"", k, v)) + } + if l.Rel != "" { + p = append(p, fmt.Sprintf("%s=\"%s\"", "rel", l.Rel)) + } + return fmt.Sprintf("<%s>; %s", l.URL, strings.Join(p, "; ")) +} + // Links is a slice of Link structs type Links []Link diff --git a/main_test.go b/main_test.go index a9ff359..8ee2389 100644 --- a/main_test.go +++ b/main_test.go @@ -66,7 +66,7 @@ func TestLinkMethods(t *testing.T) { } -func testLinksMethods(t *testing.T) { +func TestLinksMethods(t *testing.T) { header := "; rel=\"next\", " + "; rel=\"stylesheet\"; pet=\"cat\", " + "; rel=\"stylesheet\"" @@ -91,7 +91,7 @@ func testLinksMethods(t *testing.T) { } -func testParseMultiple(t *testing.T) { +func TestParseMultiple(t *testing.T) { headers := []string{ "; rel=\"next\"", "; rel=\"last\"", @@ -103,3 +103,31 @@ func testParseMultiple(t *testing.T) { t.Errorf("Should have returned 2 links") } } + +func TestLinkToString(t *testing.T) { + l := Link{ + URL: "http://example.com/page/2", + Rel: "next", + } + + have := l.String() + + want := "; rel=\"next\"" + if have != want { + t.Errorf("Want `%s`; have `%s`", want, have) + } + + parsed := Parse(have) + + if len(parsed) != 1 { + t.Errorf("Expected only 1 link") + } + + if parsed[0].URL != l.URL { + t.Errorf("Re-parsed link header should have matching URL, but has `%s`", parsed[0].URL) + } + + if parsed[0].Rel != l.Rel { + t.Errorf("Re-parsed link header should have matching rel, but has `%s`", parsed[0].Rel) + } +}