Skip to content

Commit

Permalink
Merge pull request #216 from vosmith/unmarshal_struct_slices
Browse files Browse the repository at this point in the history
Add support for struct slices
  • Loading branch information
asciimoo committed Aug 28, 2018
2 parents 06fbb2c + f1db7eb commit a3a4941
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 a3a4941

Please sign in to comment.