package data import ( "encoding/gob" "fmt" "os" "sync" "git.streifling.com/jason/rss" ) type Channel struct { addCh chan *rss.Item setCh chan rss.Channel getCh chan rss.Channel channel rss.Channel wg sync.WaitGroup } func initChannel() *Channel { return &Channel{ addCh: make(chan *rss.Item), setCh: make(chan rss.Channel), getCh: make(chan rss.Channel), channel: rss.Channel{ Items: make([]*rss.Item, 0), }, } } func (c *Channel) start() { c.wg.Done() for { select { case item := <-c.addCh: c.channel.Items = append(c.channel.Items, item) case c.getCh <- c.channel: case c.channel = <-c.setCh: } } } func NewChannel(title, link, desc string) *Channel { channel := initChannel() channel.channel = rss.Channel{ Title: title, Link: link, Description: desc, } channel.wg.Add(1) go channel.start() channel.wg.Wait() return channel } func (c *Channel) Get() rss.Channel { return <-c.getCh } func (f *Channel) Set(channel rss.Channel) { f.setCh <- channel } func LoadChannel(filename string) (*Channel, error) { file, err := os.Open(filename) if err != nil { return nil, fmt.Errorf("error opening file %v: %v", filename, err) } defer file.Close() tmpChannel := new(rss.Channel) if err = gob.NewDecoder(file).Decode(tmpChannel); err != nil { return nil, fmt.Errorf("error decoding channel from file %v: %v", filename, err) } channel := initChannel() channel.wg.Add(1) go channel.start() channel.wg.Wait() channel.Set(*tmpChannel) return channel, nil } func (c *Channel) 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() channel := c.Get() if err = gob.NewEncoder(file).Encode(channel); err != nil { return fmt.Errorf("error encoding file %v: %v", filename, err) } return nil } func (c *Channel) Add(i *rss.Item) { c.addCh <- i }