♻️ Improved searching property in nested properties
This commit is contained in:
parent
90880719cb
commit
8bee5c8559
|
@ -100,15 +100,7 @@ func ExtractProperty(resp *http.Response, itemType, key string) []interface{} {
|
||||||
Host: string(resp.Header.Peek(http.HeaderHost)),
|
Host: string(resp.Header.Peek(http.HeaderHost)),
|
||||||
})
|
})
|
||||||
|
|
||||||
for _, item := range data.Items {
|
return findProperty(data.Items, itemType, key)
|
||||||
if !contains(item.Type, itemType) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return item.Properties[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func contains(src []string, find string) bool {
|
func contains(src []string, find string) bool {
|
||||||
|
@ -122,3 +114,20 @@ func contains(src []string, find string) bool {
|
||||||
|
|
||||||
return false
|
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
|
||||||
|
}
|
||||||
|
|
|
@ -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"})
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue