Skip to content

Commit a3a4941

Browse files
authored
Merge pull request #216 from vosmith/unmarshal_struct_slices
Add support for struct slices
2 parents 06fbb2c + f1db7eb commit a3a4941

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

unmarshal.go

+6
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ func unmarshalSlice(s *goquery.Selection, selector, htmlAttr string, attrV refle
150150
UnmarshalHTML(someVal.Interface(), innerSel)
151151
attrV.Set(reflect.Append(attrV, someVal))
152152
})
153+
case reflect.Struct:
154+
s.Find(selector).Each(func(_ int, innerSel *goquery.Selection) {
155+
someVal := reflect.New(attrV.Type().Elem())
156+
UnmarshalHTML(someVal.Interface(), innerSel)
157+
attrV.Set(reflect.Append(attrV, reflect.Indirect(someVal)))
158+
})
153159
default:
154160
return errors.New("Invalid slice type")
155161
}

unmarshal_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,31 @@ func TestPointerSliceUnmarshall(t *testing.T) {
9999
}
100100

101101
}
102+
103+
func TestStructSliceUnmarshall(t *testing.T) {
104+
type info struct {
105+
Text string `selector:"span"`
106+
}
107+
type object struct {
108+
Info []info `selector:"li.info"`
109+
}
110+
111+
doc, _ := goquery.NewDocumentFromReader(bytes.NewBuffer(pointerSliceTestData))
112+
e := HTMLElement{DOM: doc.First()}
113+
o := object{}
114+
err := e.Unmarshal(&o)
115+
if err != nil {
116+
t.Fatalf("Failed to unmarshal page: %s\n", err.Error())
117+
}
118+
119+
if len(o.Info) != 2 {
120+
t.Errorf("Invalid length for Info: %d, expected 2", len(o.Info))
121+
}
122+
if o.Info[0].Text != "Info 1" {
123+
t.Errorf("Invalid data for Info.[0].Text: %s, expected Info 1", o.Info[0].Text)
124+
}
125+
if o.Info[1].Text != "Info 2" {
126+
t.Errorf("Invalid data for Info.[1].Text: %s, expected Info 2", o.Info[1].Text)
127+
}
128+
129+
}

0 commit comments

Comments
 (0)