forked from ungerik/go-rss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rss.go
99 lines (84 loc) · 2.17 KB
/
rss.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
99
/**
* Simple RSS parser, tested with various feeds.
*/
package rss
import (
"encoding/xml"
"net/http"
"time"
"github.com/plar/go-charset/charset"
_ "github.com/plar/go-charset/data"
)
const (
wordpressDateFormat = "Mon, 02 Jan 2006 15:04:05 -0700"
)
type Fetcher interface {
Get(url string) (resp *http.Response, err error)
}
type Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language"`
LastBuildDate Date `xml:"lastBuildDate"`
Item []Item `xml:"item"`
}
type ItemEnclosure struct {
URL string `xml:"url,attr"`
Type string `xml:"type,attr"`
}
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Comments string `xml:"comments"`
PubDate Date `xml:"pubDate"`
GUID string `xml:"guid"`
Category []string `xml:"category"`
Enclosure ItemEnclosure `xml:"enclosure"`
Description string `xml:"description"`
Content string `xml:"content"`
}
type Date string
func (self Date) Parse() (time.Time, error) {
t, err := self.ParseWithFormat(wordpressDateFormat)
if err != nil {
t, err = self.ParseWithFormat(time.RFC822) // RSS 2.0 spec
}
return t, err
}
func (self Date) ParseWithFormat(format string) (time.Time, error) {
return time.Parse(format, string(self))
}
func (self Date) Format(format string) (string, error) {
t, err := self.Parse()
if err != nil {
return "", err
}
return t.Format(format), nil
}
func (self Date) MustFormat(format string) string {
s, err := self.Format(format)
if err != nil {
return err.Error()
}
return s
}
func Read(url string) (*Channel, error) {
return ReadWithClient(url, http.DefaultClient)
}
func ReadWithClient(url string, client Fetcher) (*Channel, error) {
response, err := client.Get(url)
if err != nil {
return nil, err
}
defer response.Body.Close()
xmlDecoder := xml.NewDecoder(response.Body)
xmlDecoder.CharsetReader = charset.NewReader
var rss struct {
Channel Channel `xml:"channel"`
}
if err = xmlDecoder.Decode(&rss); err != nil {
return nil, err
}
return &rss.Channel, nil
}