1// This program is free software: you can redistribute it and/or modify2// it under the terms of the GNU General Public License as published by3// the Free Software Foundation, either version 3 of the License, or4// (at your option) any later version.5//6// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License for more details.10//11// You should have received a copy of the GNU General Public License12// along with this program. If not, see <http://www.gnu.org/licenses/>.13//14// This is a slightly modified version of 'encoding/xml/read_test.go'.15// Copyright 2009 The Go Authors. All rights reserved. Use of this16// source code is governed by a BSD-style license that can be found in17// the LICENSE file.1819package feedparser2021import (22 "io"23 "io/ioutil"24 "sort"25 "time"26)2728// parseFunc describes a function which implements a feed parser.29type parseFunc func([]byte) (Feed, error)3031// parsers lists all known feed parsers.32var parsers = []parseFunc{parseAtom, parseRss}3334// Feed represents a generic feed.35type Feed struct {36 // Title for the feed.37 Title string3839 // Feed type (either atom or rss).40 Type string4142 // URL to the website.43 Link string4445 // Description or subtitle for the feed.46 Description string4748 // Categories the feed belongs to.49 Categories []string5051 // Email address of the feed author.52 Author string5354 // Last time the feed was updated.55 Updated time.Time5657 // URL to image for the feed.58 Image string5960 // Software used to generate the feed.61 Generator string6263 // Information about rights, for example copyrights.64 Rights string6566 // Feed Items67 Items []Item68}6970// Item represents a generic feed item.71type Item struct {72 // Universally unique item ID.73 ID string7475 // Title of the item.76 Title string7778 // URL for the item.79 Link string8081 // Content of the item.82 Content string8384 // Email address of the item author.85 Author string8687 // Categories the item belongs to.88 Categories []string8990 // Time the item was published.91 PubDate time.Time9293 // URL to media attachment.94 Attachment string95}9697// Parse tries to parse the content of the given reader. It also sorts all items98// by there publication date. Meaning that the first item is guaranteed to be99// the most recent one.100func Parse(r io.Reader) (f Feed, err error) {101 data, err := ioutil.ReadAll(r)102 if err != nil {103 return104 }105106 for _, p := range parsers {107 f, err = p(data)108 if err == nil {109 break110 }111 }112113 if err != nil {114 return115 }116117 sort.Sort(byDate(f.Items))118 return119}