improved header parsing

This commit is contained in:
Niko Abeler 2022-09-06 21:17:25 +02:00
parent de017b86f9
commit 5596b578f4
2 changed files with 36 additions and 9 deletions

View File

@ -151,16 +151,26 @@ func (OwlHtmlParser) GetWebmentionEndpoint(resp *http.Response) (string, error)
requestUrl := resp.Request.URL requestUrl := resp.Request.URL
// Check link headers // Check link headers
for _, link := range resp.Header["Link"] { for _, linkHeader := range resp.Header["Link"] {
if strings.Contains(link, "rel=\"webmention\"") || strings.Contains(link, "rel=webmention") { linkHeaderParts := strings.Split(linkHeader, ",")
link := strings.Split(link, ";")[0] for _, linkHeaderPart := range linkHeaderParts {
link = strings.Trim(link, "<>") linkHeaderPart = strings.TrimSpace(linkHeaderPart)
linkUrl, err := url.Parse(link) params := strings.Split(linkHeaderPart, ";")
if err != nil { if len(params) != 2 {
return "", err continue
}
for _, param := range params[1:] {
param = strings.TrimSpace(param)
if strings.Contains(param, "webmention") {
link := strings.Split(params[0], ";")[0]
link = strings.Trim(link, "<>")
linkUrl, err := url.Parse(link)
if err != nil {
return "", err
}
return requestUrl.ResolveReference(linkUrl).String(), nil
}
} }
return requestUrl.ResolveReference(linkUrl).String(), nil
} }
} }

View File

@ -103,6 +103,23 @@ func TestGetWebmentionEndpointLinkHeader(t *testing.T) {
} }
} }
func TestGetWebmentionEndpointLinkHeaderCommas(t *testing.T) {
html := []byte("")
parser := &owl.OwlHtmlParser{}
resp := constructResponse(html)
resp.Header = http.Header{
"Link": []string{"<https://webmention.rocks/test/19/webmention/error>; rel=\"other\", <https://webmention.rocks/test/19/webmention>; rel=\"webmention\""},
}
endpoint, err := parser.GetWebmentionEndpoint(resp)
if err != nil {
t.Errorf("Unable to parse feed: %v", err)
}
if endpoint != "https://webmention.rocks/test/19/webmention" {
t.Errorf("Wrong endpoint. Expected %v, got %v", "https://webmention.rocks/test/19/webmention", endpoint)
}
}
func TestGetWebmentionEndpointRelativeLink(t *testing.T) { func TestGetWebmentionEndpointRelativeLink(t *testing.T) {
html := []byte("<link rel=\"webmention\" href=\"/webmention\" />") html := []byte("<link rel=\"webmention\" href=\"/webmention\" />")
parser := &owl.OwlHtmlParser{} parser := &owl.OwlHtmlParser{}