go-rssreader/rssparser.go

113 lines
3.1 KiB
Go

package rssreader
import (
"encoding/xml"
"time"
)
// --------------------------------------------------
// Define RSS Types
// They consist of the RSS itself, Channel, and Item
// --------------------------------------------------
type RSSFeed struct {
XMLName xml.Name `xml:"rss"`
Channel *Channel
}
type Channel struct {
XMLName xml.Name `xml:"channel"`
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language"`
Copyright string `xml:"copyright"`
ManagingEditor string `xml:"managingEditor"`
WebMaster string `xml:"webMaster"`
PubDate RSSTime `xml:"pubDate"`
LastBuildDate string `xml:"lastBuildDate"`
Category []Category `xml:"category"`
Generator string `xml:"generator"`
Docs string `xml:"docs"`
Cloud string `xml:"cloud"`
Ttl string `xml:"ttl"`
Image Image `xml:"image"`
Rating string `xml:"rating"`
TextInput TextInput `xml:"textInput"`
SkipHours string `xml:"skipHours"`
SkipDays string `xml:"skipDays"`
Items []Item `xml:"item"`
}
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Author string `xml:"author"`
Category []Category `xml:"category"`
Comments string `xml:"comments"`
Enclosure Enclosure `xml:"enclosure"`
Guid string `xml:"guid"`
PubDate RSSTime `xml:"pubDate"`
Source string `xml:"source"`
}
// --------------------------------------------------
// Define Type helpers
// --------------------------------------------------
// RSSTime is needed to cast dates during unmarshmalling
type RSSTime struct {
time.Time
}
func (t *RSSTime) UnmarshalText(b []byte) error {
const longForm = "Mon, 02 Jan 2006 15:04:05 -0700"
parsed, err := time.Parse(longForm, string(b))
if err != nil {
return nil
}
*t = RSSTime{parsed}
return nil
}
// --------------------------------------------------
// Define lower Types
// RSS defines smaller optional structures in
// the specification
// --------------------------------------------------
type Image struct {
Url string `xml:"url"`
Title string `xml:"title"`
Link string `xml:"link"`
Width int `xml:"width"`
Height int `xml:"height"`
Description string `xml:"description"`
}
type TextInput struct {
Title string `xml:"title"`
Description string `xml:"description"`
Name string `xml:"Name"`
Link string `xml:"link"`
}
type Enclosure struct {
Url string `xml:"url,attr"`
Length int `xml:"length,attr"`
Type string `xml:"type,attr"`
}
type Category struct {
Domain string `xml:"domain,attr"`
}
// --------------------------------------------------
// Library Functions
// --------------------------------------------------
func Parse(xml_content []byte) (*Channel, error) {
var feed RSSFeed
xml.Unmarshal(xml_content, &feed)
return feed.Channel, nil
}