cpolis/cmd/data/rss.go

77 lines
1.3 KiB
Go

package data
import (
"encoding/gob"
"fmt"
"os"
"github.com/gorilla/feeds"
)
type Feed struct {
feeds.Feed
addChan chan *feeds.Item
}
func (f *Feed) start() {
for item := range f.addChan {
f.Items = append(f.Items, item)
}
}
func NewFeed(title, link, desc string) *Feed {
feed := &Feed{
Feed: feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
addChan: make(chan *feeds.Item),
}
feed.start()
return feed
}
func (f *Feed) Close() {
close(f.addChan)
}
func OpenFeed(filename string) (*Feed, error) {
file, err := os.Open(filename)
if err != nil {
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 {
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
feed.addChan = make(chan *feeds.Item)
feed.start()
return feed, nil
}
func (f *Feed) Save(filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file %v: %v", filename, err)
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(f.Feed)
if err != nil {
return fmt.Errorf("error encoding file %v: %v", filename, err)
}
return nil
}
func (f *Feed) Add(i *feeds.Item) {
f.addChan <- i
}