Skip to content

Commit

Permalink
Add support for struct slices
Browse files Browse the repository at this point in the history
This commit continues the work done in #205 by adding support for slices of structs.
Closes #197
  • Loading branch information
vosmith committed Aug 28, 2018
1 parent 06fbb2c commit f1db7eb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ func unmarshalSlice(s *goquery.Selection, selector, htmlAttr string, attrV refle
UnmarshalHTML(someVal.Interface(), innerSel)
attrV.Set(reflect.Append(attrV, someVal))
})
case reflect.Struct:
s.Find(selector).Each(func(_ int, innerSel *goquery.Selection) {
someVal := reflect.New(attrV.Type().Elem())
UnmarshalHTML(someVal.Interface(), innerSel)
attrV.Set(reflect.Append(attrV, reflect.Indirect(someVal)))
})
default:
return errors.New("Invalid slice type")
}
Expand Down
28 changes: 28 additions & 0 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,31 @@ func TestPointerSliceUnmarshall(t *testing.T) {
}

}

func TestStructSliceUnmarshall(t *testing.T) {
type info struct {
Text string `selector:"span"`
}
type object struct {
Info []info `selector:"li.info"`
}

doc, _ := goquery.NewDocumentFromReader(bytes.NewBuffer(pointerSliceTestData))
e := HTMLElement{DOM: doc.First()}
o := object{}
err := e.Unmarshal(&o)
if err != nil {
t.Fatalf("Failed to unmarshal page: %s\n", err.Error())
}

if len(o.Info) != 2 {
t.Errorf("Invalid length for Info: %d, expected 2", len(o.Info))
}
if o.Info[0].Text != "Info 1" {
t.Errorf("Invalid data for Info.[0].Text: %s, expected Info 1", o.Info[0].Text)
}
if o.Info[1].Text != "Info 2" {
t.Errorf("Invalid data for Info.[1].Text: %s, expected Info 2", o.Info[1].Text)
}

}

0 comments on commit f1db7eb

Please sign in to comment.