### Parse Feed with Context and Timeout using Gofeed
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet shows how to parse a feed from a URL while incorporating context for timeout management. It creates a context with a specified duration (60 seconds in this example) and passes it to the `ParseURLWithContext` method. This allows for graceful cancellation of the feed parsing operation if it takes too long, preventing resource exhaustion. The example prints a success message upon parsing.
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/mmcdole/gofeed"
)
func main() {
// Create context with 60 second timeout
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext("http://feeds.example.com/feed.xml", ctx)
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Successfully parsed: %s\n", feed.Title)
}
```
--------------------------------
### Handle Feed Items with Images and Enclosures in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet demonstrates how to access and print feed-level images, item-level images, and enclosures (like audio or video files) from an RSS or Atom feed using the gofeed library. It parses a feed from a URL and iterates through its items to extract media-related information. Ensure the gofeed library is installed.
```Go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.example.com/podcast.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
// Feed-level image
if feed.Image != nil {
fmt.Printf("Feed Image URL: %s\n", feed.Image.URL)
fmt.Printf("Feed Image Title: %s\n", feed.Image.Title)
}
// Process items
for _, item := range feed.Items {
fmt.Printf("\nItem: %s\n", item.Title)
// Item image
if item.Image != nil {
fmt.Printf(" Image: %s\n", item.Image.URL)
}
// Enclosures (audio, video, files)
for _, enclosure := range item.Enclosures {
fmt.Printf(" Enclosure:\n")
fmt.Printf(" URL: %s\n", enclosure.URL)
fmt.Printf(" Type: %s\n", enclosure.Type)
fmt.Printf(" Length: %s bytes\n", enclosure.Length)
}
}
}
```
--------------------------------
### Create Custom RSS Translator in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code shows how to implement a custom translator for RSS feeds by embedding the default translator and overriding specific translation logic. The example customizes author prioritization and adds custom field processing based on the generator information. This allows for fine-grained control over how feed data is mapped to the universal feed structure.
```go
package main
import (
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
"github.com/mmcdole/gofeed/rss"
)
// CustomRSSTranslator embeds the default translator
type CustomRSSTranslator struct {
defaultTranslator *gofeed.DefaultRSSTranslator
}
func NewCustomRSSTranslator() *CustomRSSTranslator {
t := &CustomRSSTranslator{}
t.defaultTranslator = &gofeed.DefaultRSSTranslator{}
return t
}
// Translate implements custom translation logic
func (ct *CustomRSSTranslator) 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")
}
// Use default translator as base
f, err := ct.defaultTranslator.Translate(rss)
if err != nil {
return nil, err
}
// Custom logic: prioritize iTunes Author over Managing Editor
if rss.ITunesExt != nil && rss.ITunesExt.Author != "" {
f.Author = &gofeed.Person{Name: rss.ITunesExt.Author}
} else if rss.ManagingEditor != "" {
f.Author = &gofeed.Person{Name: rss.ManagingEditor}
}
// Custom logic: add custom field processing
if rss.Generator != "" {
if f.Custom == nil {
f.Custom = make(map[string]string)
}
f.Custom["generator_info"] = fmt.Sprintf("Generated by: %s", rss.Generator)
}
return f, nil
}
func main() {
feedData := `
Custom Translator Exampleeditor@example.com (Managing Editor)Podcast AuthorCustom Generator v1.0`
fp := gofeed.NewParser()
fp.RSSTranslator = NewCustomRSSTranslator()
feed, err := fp.ParseString(feedData)
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Title: %s\n", feed.Title)
if feed.Author != nil {
fmt.Printf("Author (prioritized): %s\n", feed.Author.Name)
}
if gen, ok := feed.Custom["generator_info"]; ok {
fmt.Printf("Custom field: %s\n", gen)
}
}
```
--------------------------------
### Parse Feed from String with Gofeed
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet illustrates how to parse feed content that is already available as a string. The Gofeed library takes the string as input and processes it into a structured feed object. It's useful when feed data is retrieved from memory, an API response, or other string-based sources. The example prints the feed's title, type, version, and the number of items.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
feedData := `
Sample Feed
http://example.com
This is a sample feedFirst Item
http://example.com/item1
Description of first itemMon, 02 Jan 2023 15:04:05 GMT`
fp := gofeed.NewParser()
feed, err := fp.ParseString(feedData)
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Title: %s\n", feed.Title)
fmt.Printf("Feed Type: %s\n", feed.FeedType)
fmt.Printf("Feed Version: %s\n", feed.FeedVersion)
fmt.Printf("Items count: %d\n", len(feed.Items))
}
```
--------------------------------
### Use Custom RSS Translator
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Applies a custom RSS translator to the gofeed parser to handle specific parsing logic. This example demonstrates how the custom translator prioritizes iTunes author information.
```go
feedData := `Ender WigginValentine Wiggin`
fp := gofeed.NewParser()
fp.RSSTranslator = NewMyCustomTranslator()
feed, _ := fp.ParseString(feedData)
fmt.Println(feed.Author) // Valentine Wiggin
```
--------------------------------
### Access Dublin Core Extensions in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
Illustrates how to retrieve Dublin Core metadata from feeds using the GoFeed library. It shows how to access Dublin Core elements at both the feed level (e.g., DC Title, DC Creator) and item level. This is useful for richer bibliographic information.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.example.com/feed.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
// Access Dublin Core feed extensions
if feed.DublinCoreExt != nil {
fmt.Println("Dublin Core Feed Metadata:")
for _, title := range feed.DublinCoreExt.Title {
fmt.Printf(" DC Title: %s\n", title)
}
for _, creator := range feed.DublinCoreExt.Creator {
fmt.Printf(" DC Creator: %s\n", creator)
}
for _, subject := range feed.DublinCoreExt.Subject {
fmt.Printf(" DC Subject: %s\n", subject)
}
for _, publisher := range feed.DublinCoreExt.Publisher {
fmt.Printf(" DC Publisher: %s\n", publisher)
}
for _, rights := range feed.DublinCoreExt.Rights {
fmt.Printf(" DC Rights: %s\n", rights)
}
}
// Access Dublin Core item extensions
for _, item := range feed.Items {
if item.DublinCoreExt != nil {
fmt.Printf("\nItem: %s\n", item.Title)
for _, creator := range item.DublinCoreExt.Creator {
fmt.Printf(" Creator: %s\n", creator)
}
}
}
}
```
--------------------------------
### Parse Feed with Custom User Agent and Authentication (Go)
Source: https://context7.com/mmcdole/gofeed/llms.txt
Configures the gofeed parser with a custom User-Agent header and basic authentication credentials for fetching protected feeds. It demonstrates setting these configurations before parsing a feed from a given URL. Error handling for the parsing process is included.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
// Set custom User-Agent
fp.UserAgent = "MyCustomAgent/1.0"
// Configure Basic Authentication
fp.AuthConfig = &gofeed.Auth{
Username: "myusername",
Password: "mypassword",
}
feed, err := fp.ParseURL("https://protected.example.com/feed.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Feed Title: %s\n", feed.Title)
}
```
--------------------------------
### Access iTunes Podcast Extensions in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
Demonstrates how to access iTunes-specific podcast metadata from feeds parsed by GoFeed. This includes feed-level extensions like Author and Summary, as well as item-level extensions such as Duration and Episode Number. It handles potential nil values for extensions.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.example.com/podcast.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
// Access iTunes feed extensions
if feed.ITunesExt != nil {
fmt.Printf("iTunes Author: %s\n", feed.ITunesExt.Author)
fmt.Printf("iTunes Summary: %s\n", feed.ITunesExt.Summary)
fmt.Printf("iTunes Subtitle: %s\n", feed.ITunesExt.Subtitle)
fmt.Printf("iTunes Image: %s\n", feed.ITunesExt.Image)
fmt.Printf("iTunes Explicit: %s\n", feed.ITunesExt.Explicit)
fmt.Printf("iTunes Type: %s\n", feed.ITunesExt.Type)
// Access iTunes owner
if feed.ITunesExt.Owner != nil {
fmt.Printf("Owner: %s (%s)\n", feed.ITunesExt.Owner.Name, feed.ITunesExt.Owner.Email)
}
// Access iTunes categories
for _, cat := range feed.ITunesExt.Categories {
fmt.Printf("Category: %s\n", cat.Text)
if cat.Subcategory != nil {
fmt.Printf(" Subcategory: %s\n", cat.Subcategory.Text)
}
}
}
// Access iTunes item extensions
for _, item := range feed.Items {
if item.ITunesExt != nil {
fmt.Printf("\nEpisode: %s\n", item.Title)
fmt.Printf(" Duration: %s\n", item.ITunesExt.Duration)
fmt.Printf(" Episode Number: %s\n", item.ITunesExt.Episode)
fmt.Printf(" Season: %s\n", item.ITunesExt.Season)
fmt.Printf(" Episode Type: %s\n", item.ITunesExt.EpisodeType)
fmt.Printf(" Explicit: %s\n", item.ITunesExt.Explicit)
}
}
}
```
--------------------------------
### Use Custom HTTP Client with gofeed in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet illustrates how to provide a custom `http.Client` to the gofeed parser for advanced configurations like setting timeouts, proxy settings, or custom TLS configurations. By assigning a custom client to `fp.Client`, you can control the HTTP requests made by the library. Requires the gofeed library and standard Go net/http package.
```Go
package main
import (
"crypto/tls"
"fmt"
"log"
"net/http"
"time"
"github.com/mmcdole/gofeed"
)
func main() {
// Create custom HTTP client with advanced settings
customClient := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS12,
},
},
}
fp := gofeed.NewParser()
fp.Client = customClient
fp.UserAgent = "MyApp/1.0"
feed, err := fp.ParseURL("https://feeds.example.com/feed.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Successfully parsed: %s\n", feed.Title)
}
```
--------------------------------
### Configure Basic Authentication
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Sets up basic authentication for the gofeed parser. This is useful when accessing feeds that require a username and password. The Auth struct holds the credentials.
```go
fp := gofeed.NewParser()
fp.AuthConfig = &gofeed.Auth{
Username: "foo",
Password: "bar",
}
```
--------------------------------
### Parse Feed from io.Reader with Gofeed
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet demonstrates parsing feed data from any source that implements the `io.Reader` interface, such as files or HTTP responses. It opens a local file, passes the file handle (which is an `io.Reader`) to the Gofeed parser, and then accesses feed metadata like title, link, updated date, and author information. This approach is flexible for various input streams.
```go
package main
import (
"fmt"
"log"
"os"
"github.com/mmcdole/gofeed"
)
func main() {
file, err := os.Open("/path/to/feed.xml")
if err != nil {
log.Fatalf("Error opening file: %v", err)
}
defer file.Close()
fp := gofeed.NewParser()
feed, err := fp.Parse(file)
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Feed: %s\n", feed.Title)
fmt.Printf("Link: %s\n", feed.Link)
fmt.Printf("Updated: %s\n", feed.Updated)
// Access author information
if feed.Author != nil {
fmt.Printf("Author: %s (%s)\n", feed.Author.Name, feed.Author.Email)
}
// Access all authors (some feeds have multiple)
for _, author := range feed.Authors {
fmt.Printf("Author: %s\n", author.Name)
}
}
```
--------------------------------
### Access Arbitrary Feed Extensions in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code demonstrates how to access raw feed extensions using the `Extensions` map provided by the gofeed library. It iterates through namespaces, elements, and their attributes and child elements. This is useful when the feed contains custom or non-standard extensions not explicitly parsed by gofeed.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.example.com/feed.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
// Access raw extensions map
if feed.Extensions != nil {
// Extensions are organized by namespace prefix
for namespace, elements := range feed.Extensions {
fmt.Printf("Namespace: %s\n", namespace)
// Each namespace has multiple elements
for elementName, extensions := range elements {
fmt.Printf(" Element: %s\n", elementName)
// Each element can appear multiple times
for _, ext := range extensions {
fmt.Printf(" Value: %s\n", ext.Value)
// Access attributes
for attrName, attrValue := range ext.Attrs {
fmt.Printf(" Attr %s: %s\n", attrName, attrValue)
}
// Access child elements
for childName, children := range ext.Children {
fmt.Printf(" Child %s:\n", childName)
for _, child := range children {
fmt.Printf(" Value: %s\n", child.Value)
}
}
}
}
}
}
}
```
--------------------------------
### Parse Feed from URL with Gofeed
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet demonstrates how to parse an RSS, Atom, or JSON feed directly from a URL using the Gofeed library. It automatically detects the feed type and fetches the content. The snippet shows how to access basic feed information like title, description, link, and iterates through the feed items to display their titles, links, and publication dates.
```go
package main
import (
"fmt"
"log"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
fmt.Printf("Feed Title: %s\n", feed.Title)
fmt.Printf("Feed Description: %s\n", feed.Description)
fmt.Printf("Feed Link: %s\n", feed.Link)
fmt.Printf("Number of items: %d\n", len(feed.Items))
// Iterate through feed items
for i, item := range feed.Items {
fmt.Printf("\nItem %d:\n", i+1)
fmt.Printf(" Title: %s\n", item.Title)
fmt.Printf(" Link: %s\n", item.Link)
fmt.Printf(" Published: %s\n", item.Published)
if item.PublishedParsed != nil {
fmt.Printf(" Published (parsed): %s\n", item.PublishedParsed.Format("2006-01-02 15:04:05"))
}
fmt.Printf(" Description: %s\n", item.Description)
}
}
```
--------------------------------
### Parse RSS Feed from URL with Custom User-Agent using gofeed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Fetches and parses an RSS feed from a URL using the gofeed universal parser, allowing customization of the User-Agent header. Setting a custom User-Agent can be useful for identifying your application to feed providers. It returns a unified gofeed.Feed object.
```go
fp := gofeed.NewParser()
fp.UserAgent = "MyCustomAgent 1.0"
feed, _ := fp.ParseURL("http://feeds.twit.tv/twit.xml")
fmt.Println(feed.Title)
```
--------------------------------
### Detect Feed Type in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet demonstrates how to detect the type of a feed (RSS, Atom, JSON, or Unknown) without parsing its entire content using the `gofeed.DetectFeedType` function. It takes an `io.Reader` as input and returns a `FeedType` constant. This is useful for quickly identifying feed formats. Requires the gofeed library.
```Go
package main
import (
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
)
func main() {
// RSS feed
rssFeed := `
RSS Feed`
feedType := gofeed.DetectFeedType(strings.NewReader(rssFeed))
fmt.Printf("Feed type: %d\n", feedType)
switch feedType {
case gofeed.FeedTypeRSS:
fmt.Println("Detected: RSS feed")
case gofeed.FeedTypeAtom:
fmt.Println("Detected: Atom feed")
case gofeed.FeedTypeJSON:
fmt.Println("Detected: JSON feed")
case gofeed.FeedTypeUnknown:
fmt.Println("Detected: Unknown feed type")
}
// Atom feed
atomFeed := `
Atom Feed`
feedType = gofeed.DetectFeedType(strings.NewReader(atomFeed))
if feedType == gofeed.FeedTypeAtom {
fmt.Println("Detected: Atom feed")
}
// JSON feed
jsonFeed := `{"version": "1.1", "title": "JSON Feed"}`
feedType = gofeed.DetectFeedType(strings.NewReader(jsonFeed))
if feedType == gofeed.FeedTypeJSON {
fmt.Println("Detected: JSON feed")
}
}
```
--------------------------------
### Implement Custom RSS Translator
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Defines a custom RSS translator that prioritizes the iTunes:author field over the managingEditor field for RSS feeds. This allows for more granular control over how feed data is translated.
```go
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 to prioritize iTunes Author over Managing Editor
if rss.ITunesExt != nil && rss.ITunesExt.Author != "" {
f.Author = rss.ITunesExt.Author
} else {
f.Author = rss.ManagingEditor
}
return f, nil
}
```
--------------------------------
### Parse Atom Feed with Specialized Parser (Go)
Source: https://context7.com/mmcdole/gofeed/llms.txt
Employs the specialized `atom.Parser` from the gofeed library to parse an Atom feed directly from a string. This method provides direct access to Atom-specific fields such as `Subtitle`, `ID`, and `Version`. The code includes essential error handling for the parsing process.
```go
package main
import (
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed/atom"
)
func main() {
feedData := `
Atom Example FeedA subtitle for the feedurn:uuid:60a76c80-d399-11d9-b93C-0003939e0af62023-12-01T18:30:02ZFirst Entryurn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a2023-12-01T18:30:02ZEntry summary text`
parser := atom.Parser{}
atomFeed, err := parser.Parse(strings.NewReader(feedData))
if err != nil {
log.Fatalf("Error parsing Atom feed: %v", err)
}
// Access Atom-specific fields
fmt.Printf("Title: %s\n", atomFeed.Title)
fmt.Printf("Subtitle: %s\n", atomFeed.Subtitle)
fmt.Printf("ID: %s\n", atomFeed.ID)
fmt.Printf("Version: %s\n", atomFeed.Version)
for _, entry := range atomFeed.Entries {
fmt.Printf("Entry: %s\n", entry.Title)
fmt.Printf(" ID: %s\n", entry.ID)
fmt.Printf(" Summary: %s\n", entry.Summary)
}
}
```
--------------------------------
### Parse RSS Feed from URL with Timeout using gofeed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Fetches and parses an RSS feed from a URL with a specified context and timeout using the gofeed universal parser. This is crucial for preventing long-running requests from blocking your application. It returns a unified gofeed.Feed object or an error if the context is cancelled.
```go
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
deferr cancel()
fp := gofeed.NewParser()
feed, _ := fp.ParseURLWithContext("http://feeds.twit.tv/twit.xml", ctx)
fmt.Println(feed.Title)
```
--------------------------------
### Parse RSS Feed from io.Reader using gofeed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Parses an RSS feed from an io.Reader interface using the gofeed universal parser. This method is flexible and can be used with files, network connections, or any source that implements io.Reader. It returns a unified gofeed.Feed object.
```go
file, _ := os.Open("/path/to/a/file.xml")
defer file.Close()
fp := gofeed.NewParser()
feed, _ := fp.Parse(file)
fmt.Println(feed.Title)
```
--------------------------------
### Parse RSS Feed with Specialized Parser (Go)
Source: https://context7.com/mmcdole/gofeed/llms.txt
Utilizes the specialized `rss.Parser` from the gofeed library to parse an RSS feed directly from a string. This allows for direct access to RSS-specific fields such as `WebMaster`, `ManagingEditor`, and `TTL`. It includes error handling for the parsing operation.
```go
package main
import (
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed/rss"
)
func main() {
feedData := `
RSS Example
http://example.com
An RSS feed examplewebmaster@example.com (Web Master)editor@example.com (Managing Editor)60Sample Itemhttp://example.com/item1Item description`
parser := rss.Parser{}
rssFeed, err := parser.Parse(strings.NewReader(feedData))
if err != nil {
log.Fatalf("Error parsing RSS feed: %v", err)
}
// Access RSS-specific fields
fmt.Printf("Title: %s\n", rssFeed.Title)
fmt.Printf("WebMaster: %s\n", rssFeed.WebMaster)
fmt.Printf("Managing Editor: %s\n", rssFeed.ManagingEditor)
fmt.Printf("TTL: %s\n", rssFeed.TTL)
fmt.Printf("Generator: %s\n", rssFeed.Generator)
for _, item := range rssFeed.Items {
fmt.Printf("Item: %s\n", item.Title)
if item.GUID != nil {
fmt.Printf(" GUID: %s (Permalink: %s)\n", item.GUID.Value, item.GUID.IsPermalink)
}
}
}
```
--------------------------------
### Parse RSS Feed from String using rss.Parser
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Parses an RSS feed specifically from a string using the specialized `rss.Parser`. This provides more granular control for RSS feeds and directly maps to RSS-specific structures, potentially offering performance benefits over the universal parser for single-format use cases. It returns an `rss.Feed` object.
```go
feedData := `example@site.com (Example Name)`
fp := rss.Parser{}
rssFeed, _ := fp.Parse(strings.NewReader(feedData))
fmt.Println(rssFeed.WebMaster)
```
--------------------------------
### Parse RSS Feed from String using gofeed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Parses an RSS feed from a given string using the gofeed universal parser. This method is useful for testing or when the feed content is available as a string in memory. It returns a unified gofeed.Feed object.
```go
feedData := `Sample Feed`
fp := gofeed.NewParser()
feed, _ := fp.ParseString(feedData)
fmt.Println(feed.Title)
```
--------------------------------
### Parse RSS Feed from URL using gofeed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Fetches and parses an RSS feed from a specified URL using the gofeed universal parser. This is a common use case for consuming external feeds. It handles the HTTP request and feed parsing, returning a unified gofeed.Feed object.
```go
fp := gofeed.NewParser()
feed, _ := fp.ParseURL("http://feeds.twit.tv/twit.xml")
fmt.Println(feed.Title)
```
--------------------------------
### Parse Atom Feed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Parses an Atom feed from a string. It uses the atom.Parser to read the feed data and prints the subtitle. Ensure the feedData string is a valid Atom feed.
```go
feedData := `Example Atom`
fp := atom.Parser{}
atomFeed, _ := fp.Parse(strings.NewReader(feedData))
fmt.Println(atomFeed.Subtitle)
```
--------------------------------
### Sort Feed Items Chronologically in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
This Go code snippet shows how to sort feed items chronologically (both oldest to newest and newest to oldest) using the built-in sort interface provided by the gofeed library. It parses a feed from a URL and then applies `sort.Sort` and `sort.Reverse` to the feed's items based on their `PublishedParsed` field. Requires the gofeed library.
```Go
package main
import (
"fmt"
"log"
"sort"
"github.com/mmcdole/gofeed"
)
func main() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.example.com/feed.xml")
if err != nil {
log.Fatalf("Error parsing feed: %v", err)
}
// Feed implements sort.Interface for sorting by PublishedParsed
// Sort from oldest to newest
sort.Sort(feed)
fmt.Println("Items sorted from oldest to newest:")
for i, item := range feed.Items {
if item.PublishedParsed != nil {
fmt.Printf("%d. %s - %s\n", i+1, item.Title,
item.PublishedParsed.Format("2006-01-02 15:04:05"))
}
}
// Sort from newest to oldest
sort.Sort(sort.Reverse(feed))
fmt.Println("\nItems sorted from newest to oldest:")
for i, item := range feed.Items {
if item.PublishedParsed != nil {
fmt.Printf("%d. %s - %s\n", i+1, item.Title,
item.PublishedParsed.Format("2006-01-02 15:04:05"))
}
}
}
```
--------------------------------
### Parse JSON Feed
Source: https://github.com/mmcdole/gofeed/blob/master/README.md
Parses a JSON feed from a string. It utilizes the json.Parser to process the feed data and prints the home page URL. The feedData must be a valid JSON feed.
```go
feedData := `{"version":"1.0", "home_page_url": "https://daringfireball.net"}`
fp := json.Parser{}
jsonFeed, _ := fp.Parse(strings.NewReader(feedData))
fmt.Println(jsonFeed.HomePageURL)
```
--------------------------------
### Parse JSON Feed with Specialized Parser in Go
Source: https://context7.com/mmcdole/gofeed/llms.txt
Parses a JSON feed using the specialized `json.Parser` from the GoFeed library. It takes a JSON string as input and outputs feed details and item information. This parser is specifically designed for JSON Feed formats.
```go
package main
import (
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed/json"
)
func main() {
feedData := `{
"version": "https://jsonfeed.org/version/1.1",
"title": "My JSON Feed",
"home_page_url": "https://example.org/",
"feed_url": "https://example.org/feed.json",
"description": "A sample JSON feed",
"items": [
{
"id": "1",
"url": "https://example.org/item1",
"title": "First Item",
"content_html": "
This is the content
",
"date_published": "2023-12-01T12:00:00Z"
}
]
}`
parser := json.Parser{}
jsonFeed, err := parser.Parse(strings.NewReader(feedData))
if err != nil {
log.Fatalf("Error parsing JSON feed: %v", err)
}
fmt.Printf("Title: %s\n", jsonFeed.Title)
fmt.Printf("Home Page: %s\n", jsonFeed.HomePageURL)
fmt.Printf("Feed URL: %s\n", jsonFeed.FeedURL)
fmt.Printf("Description: %s\n", jsonFeed.Description)
for _, item := range jsonFeed.Items {
fmt.Printf("\nItem: %s\n", item.Title)
fmt.Printf(" URL: %s\n", item.URL)
fmt.Printf(" Content: %s\n", item.ContentHTML)
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.