Implement a Custom Translator
masterTo control how specific feed types are converted into the universal gofeed.Feed model, you can implement the gofeed.Translator interface. This is useful for prioritizing certain fields or handling custom logic during the translation process.
- Create a struct that embeds a default translator (e.g.,
*gofeed.DefaultRSSTranslator). - Override the
Translate(feed interface{}) (*gofeed.Feed, error)method. - Assign your custom translator to the corresponding field on the
gofeed.Parser(e.g.,fp.RSSTranslator).
type MyCustomTranslator struct {
defaultTranslator *gofeed.DefaultRSSTranslator
}
func NewMyCustomTranslator() *MyCustomTranslator {
t := &MyCustomTranslator{}
t.defaultTranslator = &gofeed.DefaultRSSTranslator{}
return t
}
func (ct *MyCustomTranslator) Translate(feed interface{}) (*gofeed.Feed, error) {
rss, found := feed.(*rss.Feed)
if !found {
return nil, fmt.Errorf("Feed did not match expected type of *rss.Feed")
}
f, err := ct.defaultTranslator.Translate(rss)
if err != nil {
return nil, err
}
// Custom logic
if rss.ITunesExt != nil && rss.ITunesExt.Author != "" {
f.Author = rss.ITunesExt.Author
} else {
f.Author = rss.ManagingEditor
}
return f, nil
}
// Usage
fp := gofeed.NewParser()
fp.RSSTranslator = NewMyCustomTranslator()