Skip to content

Commit ff440e3

Browse files
committed
better unmarshaling of multiple link elements
1 parent ccc37f5 commit ff440e3

File tree

2 files changed

+34
-15
lines changed

2 files changed

+34
-15
lines changed

main.go

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (f *RSSFeed) Feed() *Feed {
151151
type AtomFeed struct {
152152
XMLName xml.Name `xml:"feed"`
153153
Title string `xml:"title"`
154-
Link Link `xml:"link"`
154+
Links []*Link `xml:"link"`
155155
Updated xmlTime `xml:"updated"`
156156
ID string `xml:"id"`
157157
Entries []*AtomEntry `xml:"entry"`
@@ -161,15 +161,22 @@ func (f *AtomFeed) Feed() *Feed {
161161
cf := &Feed{
162162
ID: f.ID,
163163
Title: f.Title,
164-
Link: f.Link.HRef,
165164
Updated: f.Updated.Time,
166165
Entries: []*FeedEntry{},
167166
}
167+
168+
for _, l := range f.Links {
169+
if l.Rel != "self" {
170+
cf.Link = l.HRef
171+
break
172+
}
173+
}
174+
168175
for _, e := range f.Entries {
169176
if e.Content == "" && e.MediaGroup != nil {
170177
e.Content = e.MediaGroup.HTML()
171178
}
172-
cf.Entries = append(cf.Entries, &FeedEntry{
179+
cf.Entries = append(cf.Entries, &FeedEntry{ // TODO e.Entry() ?
173180
Title: e.Title,
174181
Link: e.Link.HRef,
175182
ID: e.ID,
@@ -223,19 +230,29 @@ func (l *Link) UnmarshalXML(d *xml.Decoder, el xml.StartElement) error {
223230
return nil
224231
}
225232

226-
if len(el.Attr) > 0 {
227-
for _, a := range el.Attr {
228-
if a.Name.Local == "href" {
229-
_, err = url.ParseRequestURI(a.Value)
230-
if err == nil {
231-
l.HRef = a.Value
232-
return nil
233-
}
234-
}
235-
}
233+
l.HRef = getXMLAttr(el, "href")
234+
l.Rel = getXMLAttr(el, "rel")
235+
l.Type = getXMLAttr(el, "type")
236+
237+
if l.HRef == "" {
238+
return fmt.Errorf("found no href content in link element %#v", el)
236239
}
237240

238-
return fmt.Errorf("found no href content in link element %#v", el)
241+
_, err = url.ParseRequestURI(l.HRef)
242+
if err != nil {
243+
return fmt.Errorf("could not parse link's href=%#v err=%w", l.HRef, err)
244+
}
245+
246+
return nil
247+
}
248+
249+
func getXMLAttr(el xml.StartElement, name string) string {
250+
for _, a := range el.Attr {
251+
if a.Name.Local == name {
252+
return a.Value
253+
}
254+
}
255+
return ""
239256
}
240257

241258
type AtomEntry struct {

main_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ func TestTakeOnRules(t *testing.T) {
1313
byt, err := ioutil.ReadFile("test-data/take-on-rules.atom")
1414
require.Nil(t, err)
1515

16-
_, err = unmarshal(byt)
16+
f, err := unmarshal(byt)
1717
require.Nil(t, err)
18+
19+
require.Equal(t, "https://takeonrules.com/", f.Link)
1820
}
1921

2022
func TestReddit(t *testing.T) {

0 commit comments

Comments
 (0)