-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeed.go
More file actions
64 lines (55 loc) · 1.34 KB
/
feed.go
File metadata and controls
64 lines (55 loc) · 1.34 KB
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
package main
import (
"context"
"encoding/xml"
"html"
"io"
"net/http"
"time"
)
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) {
httpClient := http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequestWithContext(ctx, "GET", feedURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "gator")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
dat, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var rssFeed RSSFeed
err = xml.Unmarshal(dat, &rssFeed)
if err != nil {
return nil, err
}
rssFeed.Channel.Title = html.UnescapeString(rssFeed.Channel.Title)
rssFeed.Channel.Description = html.UnescapeString(rssFeed.Channel.Description)
for i, item := range rssFeed.Channel.Item {
item.Title = html.UnescapeString(item.Title)
item.Description = html.UnescapeString(item.Description)
rssFeed.Channel.Item[i] = item
}
return &rssFeed, nil
}