58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package rss
|
|
|
|
import (
|
|
"context"
|
|
"encoding/xml"
|
|
"html"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
type Feed struct {
|
|
Channel struct {
|
|
Title string `xml:"title"`
|
|
Link string `xml:"link"`
|
|
Description string `xml:"description"`
|
|
Item []Item `xml:"item"`
|
|
} `xml:"channel"`
|
|
}
|
|
|
|
type Item struct {
|
|
Title string `xml:"title"`
|
|
Link string `xml:"link"`
|
|
Description string `xml:"description"`
|
|
PubDate string `xml:"pubDate"`
|
|
}
|
|
|
|
func FetchFeed(ctx context.Context, feedURL string) (*Feed, error) {
|
|
req, err := http.NewRequestWithContext(ctx, "GET", feedURL, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("User-Agent", "gator")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
res, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var feed Feed
|
|
err = xml.Unmarshal(res, &feed)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
feed.Channel.Title = html.UnescapeString(feed.Channel.Title)
|
|
feed.Channel.Link = html.UnescapeString(feed.Channel.Link)
|
|
feed.Channel.Description = html.UnescapeString(feed.Channel.Description)
|
|
for i, _ := range feed.Channel.Item {
|
|
feed.Channel.Item[i].Link = html.UnescapeString(feed.Channel.Item[i].Link)
|
|
feed.Channel.Item[i].Description = html.UnescapeString(feed.Channel.Item[i].Description)
|
|
feed.Channel.Item[i].PubDate = html.UnescapeString(feed.Channel.Item[i].PubDate)
|
|
feed.Channel.Item[i].Title = html.UnescapeString(feed.Channel.Item[i].Title)
|
|
}
|
|
return &feed, nil
|
|
}
|