cpolis/cmd/data/rss.go

67 lines
1.1 KiB
Go
Raw Normal View History

2024-02-24 14:49:29 +01:00
package data
2024-02-18 12:41:49 +01:00
import (
"encoding/gob"
2024-02-18 12:41:49 +01:00
"fmt"
"os"
2024-03-01 11:30:31 +01:00
"sync"
2024-02-18 12:41:49 +01:00
"github.com/gorilla/feeds"
)
type Feed struct {
feeds.Feed
2024-03-01 11:30:31 +01:00
sync.Mutex
2024-02-18 12:41:49 +01:00
}
func NewFeed(title, link, desc string) *Feed {
2024-03-01 11:30:31 +01:00
return &Feed{
Feed: feeds.Feed{
2024-02-18 12:41:49 +01:00
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
}
}
func OpenFeed(filename string) (*Feed, error) {
file, err := os.Open(filename)
if err != nil {
2024-02-22 15:23:29 +01:00
return nil, fmt.Errorf("error opening file %v: %v", filename, err)
}
defer file.Close()
feed := new(Feed)
decoder := gob.NewDecoder(file)
err = decoder.Decode(&feed.Feed)
if err != nil {
2024-02-22 15:23:29 +01:00
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
return feed, nil
}
func (f *Feed) Save(filename string) error {
2024-02-24 14:49:29 +01:00
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file %v: %v", filename, err)
2024-02-18 12:41:49 +01:00
}
2024-02-24 14:49:29 +01:00
defer file.Close()
2024-02-18 12:41:49 +01:00
2024-02-24 14:49:29 +01:00
encoder := gob.NewEncoder(file)
2024-03-01 11:30:31 +01:00
f.Lock()
err = encoder.Encode(f.Feed)
2024-03-01 11:30:31 +01:00
f.Unlock()
2024-02-18 12:41:49 +01:00
if err != nil {
2024-02-24 14:49:29 +01:00
return fmt.Errorf("error encoding file %v: %v", filename, err)
2024-02-18 12:41:49 +01:00
}
return nil
}
func (f *Feed) Add(i *feeds.Item) {
2024-03-01 11:30:31 +01:00
f.Lock()
f.Items = append(f.Items, i)
f.Unlock()
}