cpolis/cmd/feed/rss.go

76 lines
1.4 KiB
Go

package feed
import (
"encoding/gob"
"fmt"
"os"
"time"
"github.com/gorilla/feeds"
)
type Feed struct {
feeds.Feed
}
func NewFeed(title, link, desc string) *Feed {
return &Feed{
Feed: feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
}
}
func SaveFeed(feed *Feed, filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error cmd/feed/rss.go SaveFeed os.Create(): %v", err)
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(feed)
if err != nil {
return fmt.Errorf("error cmd/feed/rss.go SaveFeed encoder.Encode(): %v", err)
}
return nil
}
func OpenFeed(filename string) (*Feed, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error cmd/feed/rss.go OpenFeed os.Open(): %v", err)
}
defer file.Close()
feed := &Feed{}
decoder := gob.NewDecoder(file)
err = decoder.Decode(feed)
if err != nil {
return nil, fmt.Errorf("error cmd/feed/rss.go OpenFeed decoder.Decode(): %v", err)
}
return feed, nil
}
func AddToFeed(feed *Feed, title, desc, content string) error {
item := feeds.Item{
Title: title,
Created: time.Now(),
Description: desc,
Content: content,
}
feed.Add(&item)
rss, err := feed.ToRss()
if err != nil {
return fmt.Errorf("error cmd/feed/rss.go AddToFeed feed.ToRss(): %v", err)
}
fmt.Println(rss)
return nil
}