62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package rss
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"encoding/xml"
|
||
|
|
"html"
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
type RSSItem struct {
|
||
|
|
Title string `xml:"title"`
|
||
|
|
Link string `xml:"link"`
|
||
|
|
Description string `xml:"description"`
|
||
|
|
PubDate string `xml:"pubDate"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type RSSChannel struct {
|
||
|
|
Title string `xml:"title"`
|
||
|
|
Link string `xml:"link"`
|
||
|
|
Description string `xml:"description"`
|
||
|
|
Item []RSSItem `xml:"item"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type RSSFeed struct {
|
||
|
|
Channel RSSChannel `xml:"channel"`
|
||
|
|
}
|
||
|
|
|
||
|
|
func FetchFeed(ctx context.Context, feedURL string) (*RSSFeed, error) {
|
||
|
|
var rssFeed RSSFeed
|
||
|
|
|
||
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
|
||
|
|
req.Header.Set("User-Agent", "gator")
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
res, err := http.DefaultClient.Do(req)
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
defer res.Body.Close()
|
||
|
|
|
||
|
|
err = xml.NewDecoder(res.Body).Decode(&rssFeed)
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
rssFeed.Channel.Title = html.UnescapeString(rssFeed.Channel.Title)
|
||
|
|
rssFeed.Channel.Description = html.UnescapeString(rssFeed.Channel.Description)
|
||
|
|
|
||
|
|
for _, item := range rssFeed.Channel.Item {
|
||
|
|
item.Title = html.UnescapeString(item.Title)
|
||
|
|
item.Description = html.UnescapeString(item.Description)
|
||
|
|
}
|
||
|
|
|
||
|
|
return &rssFeed, nil
|
||
|
|
}
|