-
Notifications
You must be signed in to change notification settings - Fork 0
/
rss.go
64 lines (51 loc) · 1.46 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
package main
import (
"encoding/xml"
"io"
"net/http"
"time"
)
type RSSFeed struct {
Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language"`
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 urlToFeed(url string) (RSSFeed, error) {
httpClient := http.Client{
Timeout: 10 * time.Second,
}
res, err := httpClient.Get(url)
if err != nil {
return RSSFeed{}, err
}
/*
res.Body.Close() is being deferred. It is a common practice to close the response body after making an HTTP request.
The Close() method is used to release any resources associated with the response body, such as network connections or file handles.
By deferring the Close() method call, we ensure that it will be executed at the end of the surrounding function,
regardless of any early returns or panics that may occur before that point. This helps prevent resource leaks and ensures proper cleanup
*/
defer res.Body.Close()
/*
reads data from an HTTP response body into a byte slice `dat`
*/
dat, err := io.ReadAll(res.Body)
if err != nil {
return RSSFeed{}, err
}
rssFeed := RSSFeed{}
err = xml.Unmarshal(dat, &rssFeed)
if err != nil {
return RSSFeed{}, err
}
return rssFeed, nil
}