-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrss.go
66 lines (54 loc) · 1.5 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
package main
import (
"context"
"encoding/xml"
"fmt"
"html"
"io"
"net/http"
)
type RSSFeed struct {
Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Item []RSSItem `xml:"item"`
} `xml:"channel"`
}
type RSSItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
}
func fetchFeed(ctx context.Context, feedURL string) (*RSSFeed, error) {
client := &http.Client{}
req, err := http.NewRequestWithContext(ctx, "GET", feedURL, nil)
if err != nil {
return &RSSFeed{}, err
}
req.Header.Set("User-Agent", "Gator")
resp, err := client.Do(req)
if err != nil {
return &RSSFeed{}, fmt.Errorf("error occurred during http request: %v", err)
}
fmt.Printf("RSSFeed retreived with status code: %v\n", resp.StatusCode)
defer resp.Body.Close()
xmlData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading data %v", err)
}
rss := &RSSFeed{}
err = xml.Unmarshal(xmlData, &rss)
if err != nil {
return &RSSFeed{}, fmt.Errorf("error Decoding xml %v", err)
}
rss.Channel.Title = html.UnescapeString(rss.Channel.Title)
rss.Channel.Description = html.UnescapeString(rss.Channel.Description)
for i, item := range rss.Channel.Item {
item.Title = html.UnescapeString(item.Title)
item.Description = html.UnescapeString(item.Description)
rss.Channel.Item[i] = item
}
return rss, nil
}