♻️ Improved searching property in nested properties

This commit is contained in:
Maxim Lebedev 2022-02-18 02:09:22 +05:00
parent 90880719cb
commit 8bee5c8559
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
2 changed files with 48 additions and 9 deletions

View File

@ -100,15 +100,7 @@ func ExtractProperty(resp *http.Response, itemType, key string) []interface{} {
Host: string(resp.Header.Peek(http.HeaderHost)),
})
for _, item := range data.Items {
if !contains(item.Type, itemType) {
continue
}
return item.Properties[key]
}
return nil
return findProperty(data.Items, itemType, key)
}
func contains(src []string, find string) bool {
@ -122,3 +114,20 @@ func contains(src []string, find string) bool {
return false
}
func findProperty(src []*microformats.Microformat, itemType, key string) []interface{} {
for _, item := range src {
if contains(item.Type, itemType) {
return item.Properties[key]
}
result := findProperty(item.Children, itemType, key)
if result == nil {
continue
}
return result
}
return nil
}

View File

@ -0,0 +1,30 @@
package util_test
import (
"testing"
http "github.com/valyala/fasthttp"
"source.toby3d.me/website/indieauth/internal/util"
)
const testBody = `<html>
<body class="h-page">
<main class="h-card">
<h1 class="p-name">Sample Name</h1>
</main>
</body>
</html>`
func TestExtractProperty(t *testing.T) {
t.Parallel()
resp := http.AcquireResponse()
defer http.ReleaseResponse(resp)
resp.SetBodyString(testBody)
results := util.ExtractProperty(resp, "h-card", "name")
if results == nil || results[0] != "Sample Name" {
t.Errorf(`ExtractProperty(resp, "h-card", "name") = %+s, want %+s`, results, []string{"Sample Name"})
}
}