package data import ( "encoding/gob" "fmt" "os" "github.com/gorilla/feeds" ) type Feed struct { addCh chan *feeds.Item openCh chan feeds.Feed saveCh chan feeds.Feed showCh chan feeds.Feed feed feeds.Feed } func (f *Feed) start() { for { select { case item := <-f.addCh: f.feed.Items = append(f.feed.Items, item) case f.saveCh <- f.feed: case tmpFeed := <-f.openCh: f.feed = tmpFeed case f.showCh <- f.feed: } } } func NewFeed(title, link, desc string) *Feed { feed := &Feed{ addCh: make(chan *feeds.Item), openCh: make(chan feeds.Feed), saveCh: make(chan feeds.Feed), showCh: make(chan feeds.Feed), feed: feeds.Feed{ Title: title, Link: &feeds.Link{Href: link}, Description: desc, }, } go feed.start() return feed } func OpenFeed(filename string) (*Feed, error) { feed := new(Feed) go feed.start() file, err := os.Open(filename) if err != nil { return nil, fmt.Errorf("error opening file %v: %v", filename, err) } defer file.Close() decoder := gob.NewDecoder(file) tmpFeed := new(feeds.Feed) err = decoder.Decode(tmpFeed) if err != nil { return nil, fmt.Errorf("error decoding file %v: %v", filename, err) } feed.openCh <- *tmpFeed 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) feed := <-f.saveCh err = encoder.Encode(feed) if err != nil { return fmt.Errorf("error encoding file %v: %v", filename, err) } return nil } func (f *Feed) Add(i *feeds.Item) { f.addCh <- i } func (f *Feed) Show() feeds.Feed { return <-f.showCh }