-
Notifications
You must be signed in to change notification settings - Fork 1
/
feed.go
98 lines (83 loc) · 2.25 KB
/
feed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package feedly
import (
"encoding/xml"
"fmt"
)
// Item represents a single item in the RSS feed.
// It contains the title, description, link, and publication date.
type Item struct {
Title string `xml:"title"`
Description string `xml:"description"`
Link string `xml:"link"`
PubDate string `xml:"pubDate"`
// media:content
// media:thumbnail
Media struct {
Content struct {
Url string `xml:"url,attr"`
}
} `xml:"media:content"`
// Content
Content string `xml:"content:encoded"`
// Categories
Categories []string `xml:"category"`
// Enclosure
Enclosure struct {
Url string `xml:"url,attr"`
} `xml:"enclosure"`
}
// Channel represents the RSS feed.
// It contains the title, description, link, and items.
type Channel struct {
Title string `xml:"title"`
Description string `xml:"description"`
Link string `xml:"link"`
Items []Item `xml:"item"`
}
type Rss struct {
// Rss represents the root of the RSS feed.
// It contains the channel.
Channel Channel `xml:"channel"`
}
type Feed struct {
// Feed represents the RSS feed.
// It contains the channel.
Channel Channel `xml:"channel"`
}
type UnMarshallError struct {
error
}
func NewRSS(src []byte) (*Rss, UnMarshallError) {
var rss Rss
err := xml.Unmarshal(src, &rss)
if err != nil {
return nil, UnMarshallError{err}
}
// check if media:content is empty
for i, item := range rss.Channel.Items {
if item.Media.Content.Url == "" {
rss.Channel.Items[i].Media.Content.Url = item.Enclosure.Url
}
}
// check if media content is empty and it to the first image in the content. img src
for i, item := range rss.Channel.Items {
if item.Media.Content.Url == "" && item.Content != "" {
var imgSrc string
_, err := fmt.Sscanf(item.Content, "<img src=\"%s\"", &imgSrc)
if err == nil {
rss.Channel.Items[i].Media.Content.Url = imgSrc
}
}
}
// check if media content is empty and it to the first image in the description. img src
for i, item := range rss.Channel.Items {
if item.Media.Content.Url == "" && item.Description != "" {
var imgSrc string
_, err := fmt.Sscanf(item.Description, "<img src=\"%s\"", &imgSrc)
if err == nil {
rss.Channel.Items[i].Media.Content.Url = imgSrc
}
}
}
return &rss, UnMarshallError{nil}
}