cpolis/cmd/data/rss.go

67 lines
1.1 KiB
Go

package data
import (
"encoding/gob"
"fmt"
"os"
"sync"
"github.com/gorilla/feeds"
)
type Feed struct {
feeds.Feed
sync.Mutex
}
func NewFeed(title, link, desc string) *Feed {
return &Feed{
Feed: feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
}
}
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)
}
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)
f.Lock()
err = encoder.Encode(f.Feed)
f.Unlock()
if err != nil {
return fmt.Errorf("error encoding file %v: %v", filename, err)
}
return nil
}
func (f *Feed) Add(i *feeds.Item) {
f.Lock()
f.Items = append(f.Items, i)
f.Unlock()
}