rss

package module
v0.0.0-...-db3567c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: Unlicense Imports: 8 Imported by: 22 modules, 23 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-rss

Go Reference Go Report Card

A simple, robust RSS and Atom feed parser for Go with comprehensive context support for cancellation and timeouts. This library provides a clean API for fetching and parsing RSS 2.0 and Atom 1.0 feeds with proper error handling, resource management, and modern Go conventions.

Features

  • RSS 2.0 and Atom 1.0 Support - Parse both major feed formats
  • Context Support - Full cancellation and timeout support using context.Context
  • Custom HTTP Clients - Use your own HTTP client configurations
  • Reddit Feed Support - Special handling for Reddit feeds with proper user agents
  • Character Encoding - Automatic detection and conversion of various encodings
  • Resource Management - Proper cleanup of HTTP response bodies
  • Comprehensive Error Handling - Detailed error messages with context
  • Modern Go Conventions - Context as first parameter, error wrapping
  • Zero Dependencies - Only uses standard library and one charset library

Installation

go get github.com/ungerik/go-rss

Quick Start

Basic RSS Feed Reading
package main

import (
    "context"
    "fmt"
    "log"
    "github.com/ungerik/go-rss"
)

func main() {
    ctx := context.Background()
    
    // Fetch an RSS feed
    resp, err := rss.Read(ctx, "https://example.com/feed.rss", false)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // Parse the RSS feed
    channel, err := rss.Regular(ctx, resp)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Channel: %s\n", channel.Title)
    fmt.Printf("Description: %s\n", channel.Description)
    
    for _, item := range channel.Item {
        fmt.Printf("- %s (%s)\n", item.Title, item.Link)
    }
}
Atom Feed Reading
package main

import (
    "context"
    "fmt"
    "log"
    "github.com/ungerik/go-rss"
)

func main() {
    ctx := context.Background()
    
    // Fetch an Atom feed
    resp, err := rss.Read(ctx, "https://example.com/feed.atom", false)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // Parse the Atom feed
    feed, err := rss.Atom(ctx, resp)
    if err != nil {
        log.Fatal(err)
    }

    for _, entry := range feed.Entry {
        fmt.Printf("- %s (Updated: %s)\n", entry.Title, entry.Updated)
    }
}

API Reference

Reading Feeds
Read(ctx context.Context, url string, reddit bool) (*http.Response, error)

Fetches an RSS or Atom feed from the given URL using the default HTTP client.

Parameters:

  • ctx - Context for cancellation and timeout control
  • url - The URL of the feed to fetch
  • reddit - Set to true for Reddit feeds to use appropriate user agent

Returns:

  • *http.Response - HTTP response (caller must close the body)
  • error - Any error that occurred during fetching
ReadWithClient(ctx context.Context, url string, client *http.Client, reddit bool) (*http.Response, error)

Fetches a feed using a custom HTTP client, allowing for custom configurations.

Use cases:

  • Custom timeouts
  • Proxy settings
  • Custom headers
  • Custom transport logic
InsecureRead(ctx context.Context, url string, reddit bool) (*http.Response, error)

Fetches a feed without SSL certificate verification.

⚠️ Warning: This disables SSL verification and should only be used in development or testing environments.

Parsing Feeds
Regular(ctx context.Context, resp *http.Response) (*Channel, error)

Parses an RSS 2.0 feed from an HTTP response.

Returns:

  • *Channel - Parsed RSS channel data
  • error - Any parsing error
Atom(ctx context.Context, resp *http.Response) (*Feed, error)

Parses an Atom 1.0 feed from an HTTP response.

Returns:

  • *Feed - Parsed Atom feed data
  • error - Any parsing error
Data Structures
Channel (RSS)
type Channel struct {
    Title         string `xml:"title"`         // Channel title
    Link          string `xml:"link"`          // Channel URL
    Description   string `xml:"description"`   // Channel description
    Language      string `xml:"language"`      // Channel language
    LastBuildDate Date   `xml:"lastBuildDate"` // Last build date
    Item          []Item `xml:"item"`          // Channel items
}
Item (RSS)
type Item struct {
    Title       string          `xml:"title"`       // Item title
    Link        string          `xml:"link"`        // Item URL
    Comments    string          `xml:"comments"`   // Comments URL
    PubDate     Date            `xml:"pubDate"`     // Publication date
    GUID        string          `xml:"guid"`        // Unique identifier
    Category    []string        `xml:"category"`   // Categories
    Enclosure   []ItemEnclosure `xml:"enclosure"`  // Media enclosures
    Description string          `xml:"description"` // Item description
    Author      string          `xml:"author"`     // Author email
    Content     string          `xml:"content"`    // Full content
    FullText    string          `xml:"full-text"`  // Complete text
}
Feed (Atom)
type Feed struct {
    Entry []Entry `xml:"entry"` // Feed entries
}

type Entry struct {
    ID      string `xml:"id"`      // Unique identifier
    Title   string `xml:"title"`  // Entry title
    Updated string `xml:"updated"` // Last updated time
}
Date Handling

The Date type provides methods for parsing dates in various formats:

// Parse using multiple common formats
t, err := item.PubDate.Parse()

// Parse with specific format
t, err := item.PubDate.ParseWithFormat(time.RFC822)

// Format parsed date
formatted, err := item.PubDate.Format("2006-01-02 15:04:05")

// Format without error handling (returns error string on failure)
formatted := item.PubDate.MustFormat("2006-01-02")

Advanced Usage

Context with Timeout
package main

import (
    "context"
    "fmt"
    "time"
    "github.com/ungerik/go-rss"
)

func main() {
    // Create context with 10 second timeout
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    resp, err := rss.Read(ctx, "https://slow-feed.com/rss", false)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    defer resp.Body.Close()

    channel, err := rss.Regular(ctx, resp)
    if err != nil {
        fmt.Printf("Parse error: %v\n", err)
        return
    }

    fmt.Printf("Successfully parsed: %s\n", channel.Title)
}
Context with Cancellation
package main

import (
    "context"
    "fmt"
    "time"
    "github.com/ungerik/go-rss"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    
    // Cancel after 5 seconds
    go func() {
        time.Sleep(5 * time.Second)
        cancel()
        fmt.Println("Operation cancelled")
    }()

    resp, err := rss.Read(ctx, "https://example.com/feed.rss", false)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    defer resp.Body.Close()

    // ... rest of processing
}
Custom HTTP Client
package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
    "github.com/ungerik/go-rss"
)

func main() {
    // Create custom HTTP client with timeout
    client := &http.Client{
        Timeout: 30 * time.Second,
        Transport: &http.Transport{
            MaxIdleConns:        10,
            IdleConnTimeout:     30 * time.Second,
            DisableCompression:  true,
        },
    }

    ctx := context.Background()
    resp, err := rss.ReadWithClient(ctx, "https://example.com/feed.rss", client, false)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    defer resp.Body.Close()

    channel, err := rss.Regular(ctx, resp)
    if err != nil {
        fmt.Printf("Parse error: %v\n", err)
        return
    }

    fmt.Printf("Channel: %s\n", channel.Title)
}
Reddit Feed Support
package main

import (
    "context"
    "fmt"
    "github.com/ungerik/go-rss"
)

func main() {
    ctx := context.Background()
    
    // Fetch Reddit feed with special user agent
    resp, err := rss.Read(ctx, "https://reddit.com/r/golang.rss", true)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    defer resp.Body.Close()

    channel, err := rss.Regular(ctx, resp)
    if err != nil {
        fmt.Printf("Parse error: %v\n", err)
        return
    }

    fmt.Printf("Reddit Channel: %s\n", channel.Title)
}
Processing Multiple Feeds
package main

import (
    "context"
    "fmt"
    "strings"
    "sync"
    "time"
    "github.com/ungerik/go-rss"
)

func main() {
    feeds := []string{
        "https://blog.golang.org/feed.atom",
        "https://example.com/feed.rss",
        "https://reddit.com/r/golang.rss",
    }

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    var wg sync.WaitGroup
    results := make(chan string, len(feeds))

    for i, feedURL := range feeds {
        wg.Add(1)
        go func(index int, url string) {
            defer wg.Done()
            
            isReddit := false
            if strings.Contains(url, "reddit.com") {
                isReddit = true
            }

            resp, err := rss.Read(ctx, url, isReddit)
            if err != nil {
                results <- fmt.Sprintf("Feed %d error: %v", index, err)
                return
            }
            defer resp.Body.Close()

            // Determine feed type and parse accordingly
            if strings.Contains(url, ".atom") || isReddit {
                feed, err := rss.Atom(ctx, resp)
                if err != nil {
                    results <- fmt.Sprintf("Feed %d parse error: %v", index, err)
                    return
                }
                results <- fmt.Sprintf("Feed %d: %d entries", index, len(feed.Entry))
            } else {
                channel, err := rss.Regular(ctx, resp)
                if err != nil {
                    results <- fmt.Sprintf("Feed %d parse error: %v", index, err)
                    return
                }
                results <- fmt.Sprintf("Feed %d: %s (%d items)", index, channel.Title, len(channel.Item))
            }
        }(i, feedURL)
    }

    go func() {
        wg.Wait()
        close(results)
    }()

    for result := range results {
        fmt.Println(result)
    }
}

Error Handling

The library provides comprehensive error handling with wrapped errors for better debugging:

resp, err := rss.Read(ctx, "https://example.com/feed.rss", false)
if err != nil {
    // Check for specific error types
    if strings.Contains(err.Error(), "context deadline exceeded") {
        fmt.Println("Request timed out")
    } else if strings.Contains(err.Error(), "context canceled") {
        fmt.Println("Request was cancelled")
    } else {
        fmt.Printf("Other error: %v\n", err)
    }
    return
}

Testing

Run the test suite:

go test -v

The tests include:

  • Feed parsing validation
  • Context cancellation testing
  • Context timeout testing
  • Error handling validation

Examples

See the example/ and examples/ directories for comprehensive usage examples:

  • example/main.go - Basic usage with context and timeout
  • examples/context/main.go - Advanced context usage patterns

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v2.0.0 (Breaking Changes)
  • Added context.Context as first parameter to all functions
  • Removed WithContext suffix variants
  • Improved error handling with wrapped errors
  • Added comprehensive documentation
  • Enhanced resource management
v1.0.0
  • Initial release with basic RSS/Atom parsing
  • Context support with WithContext variants
  • Reddit feed support

Documentation

Overview

Package rss provides a simple RSS and Atom feed parser with context support. It supports RSS 2.0 and Atom feeds with proper error handling, timeout support, and resource management.

Basic usage:

ctx := context.Background()
resp, err := rss.Read(ctx, "https://example.com/feed.rss", false)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

channel, err := rss.Regular(ctx, resp)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Channel: %s\n", channel.Title)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InsecureRead

func InsecureRead(ctx context.Context, url string, reddit bool) (*http.Response, error)

InsecureRead fetches an RSS or Atom feed from the given URL using an HTTP client that skips SSL certificate verification. This should only be used in development or testing environments where SSL verification is not critical.

WARNING: This function disables SSL certificate verification, making it vulnerable to man-in-the-middle attacks. Do not use in production environments.

func Read

func Read(ctx context.Context, url string, reddit bool) (*http.Response, error)

Read fetches an RSS or Atom feed from the given URL using the default HTTP client. The context is used for cancellation and timeout control. The reddit parameter should be set to true when fetching Reddit feeds to use the appropriate user agent header.

Returns an HTTP response that should be closed by the caller. The response body should be passed to either Regular() or Atom() for parsing.

func ReadWithClient

func ReadWithClient(ctx context.Context, url string, client *http.Client, reddit bool) (*http.Response, error)

ReadWithClient fetches an RSS or Atom feed from the given URL using a custom HTTP client. This allows for custom transport configurations, timeouts, and other HTTP client settings. The context is used for cancellation and timeout control.

The client parameter allows you to customize the HTTP behavior, such as: - Setting custom timeouts - Configuring proxy settings - Adding custom headers - Implementing custom transport logic

Returns an HTTP response that should be closed by the caller. The response body should be passed to either Regular() or Atom() for parsing.

Types

type Channel

type Channel struct {
	// Title is the name of the channel
	Title string `xml:"title"`

	// Link is the URL to the HTML website corresponding to the channel
	Link string `xml:"link"`

	// Description is a phrase or sentence describing the channel
	Description string `xml:"description"`

	// Language is the language the channel is written in
	Language string `xml:"language"`

	// LastBuildDate indicates the last time the content of the channel changed
	LastBuildDate Date `xml:"lastBuildDate"`

	// Item is a slice of items in the channel
	Item []Item `xml:"item"`
}

Channel represents an RSS channel containing metadata and items. It follows the RSS 2.0 specification structure.

func ParseRegular

func ParseRegular(ctx context.Context, r io.Reader) (*Channel, error)

ParseRegular parses an RSS 2.0 feed from an io.Reader. It expects the reader to contain valid RSS XML. The context is used for cancellation control during parsing.

The function automatically handles character encoding detection and conversion using the go-charset library, supporting various encodings commonly found in RSS feeds.

Returns a Channel struct containing the parsed RSS data and any error that occurred. The reader is not closed by this function; the caller is responsible for closing it.

func Regular

func Regular(ctx context.Context, resp *http.Response) (*Channel, error)

Regular parses an RSS 2.0 feed from an HTTP response. It expects the response body to contain valid RSS XML. The context is used for cancellation control during parsing.

The function automatically handles character encoding detection and conversion using the go-charset library, supporting various encodings commonly found in RSS feeds.

Returns a Channel struct containing the parsed RSS data and any error that occurred. The response body is automatically closed after parsing.

type Date

type Date string

Date represents a date string from RSS/Atom feeds. It provides methods for parsing dates in various formats commonly found in RSS and Atom feeds.

func (Date) Format

func (d Date) Format(format string) (string, error)

Format parses the date and formats it using the specified format string. It first calls Parse() to convert the date string to a time.Time, then formats it using the provided format.

Returns the formatted date string and any error that occurred.

func (Date) MustFormat

func (d Date) MustFormat(format string) string

MustFormat parses the date and formats it using the specified format string. Unlike Format(), this function does not return an error. If parsing fails, it returns the error message as a string instead of panicking.

This is useful when you want to display a date but don't want to handle parsing errors explicitly.

func (Date) Parse

func (d Date) Parse() (time.Time, error)

Parse attempts to parse the date string using multiple common formats. It tries formats in the following order: 1. WordPress format (Mon, 02 Jan 2006 15:04:05 -0700) 2. RFC822 format with a named zone 3. RFC1123 format with a named zone 4. RFC822 format with a numeric zone 5. RFC3339 format (Atom standard)

Returns the parsed time and any error that occurred.

func (Date) ParseWithFormat

func (d Date) ParseWithFormat(format string) (time.Time, error)

ParseWithFormat parses the date string using the specified format. The format should follow Go's time format layout (reference time: Mon Jan 2 15:04:05 MST 2006).

Returns the parsed time and any error that occurred.

type Entry

type Entry struct {
	// ID is a permanent, universally unique identifier for the entry
	ID string `xml:"id"`

	// Title is the title of the entry
	Title string `xml:"title"`

	// Updated is the time when the entry was last modified
	Updated string `xml:"updated"`
}

Entry represents a single entry in an Atom feed. Each entry typically represents a blog post, article, or other piece of content.

type Feed

type Feed struct {
	// Entry is a slice of entries in the feed
	Entry []Entry `xml:"entry"`
}

Feed represents an Atom feed containing entries. It follows the Atom 1.0 specification structure.

func Atom

func Atom(ctx context.Context, resp *http.Response) (*Feed, error)

Atom parses an Atom 1.0 feed from an HTTP response. It expects the response body to contain valid Atom XML. The context is used for cancellation control during parsing.

The function automatically handles character encoding detection and conversion using the go-charset library, supporting various encodings commonly found in Atom feeds.

Returns a Feed struct containing the parsed Atom data and any error that occurred. The response body is automatically closed after parsing.

func ParseAtom

func ParseAtom(ctx context.Context, r io.Reader) (*Feed, error)

ParseAtom parses an Atom 1.0 feed from an io.Reader. It expects the reader to contain valid Atom XML. The context is used for cancellation control during parsing.

The function automatically handles character encoding detection and conversion using the go-charset library, supporting various encodings commonly found in Atom feeds.

Returns a Feed struct containing the parsed Atom data and any error that occurred. The reader is not closed by this function; the caller is responsible for closing it.

type Fetcher

type Fetcher interface {
	// Get fetches a resource from the given URL using the provided context.
	// It returns an HTTP response and any error that occurred during the fetch.
	Get(ctx context.Context, url string) (resp *http.Response, err error)
}

Fetcher defines the interface for fetching HTTP resources. This interface allows for custom implementations of HTTP clients while maintaining compatibility with the RSS parsing functions.

type Item

type Item struct {
	// Title is the title of the item
	Title string `xml:"title"`

	// Link is the URL of the item
	Link string `xml:"link"`

	// Comments is the URL of a page for comments relating to the item
	Comments string `xml:"comments"`

	// PubDate is the publication date of the item
	PubDate Date `xml:"pubDate"`

	// GUID is a string that uniquely identifies the item
	GUID string `xml:"guid"`

	// Category is a list of categories that the item belongs to
	Category []string `xml:"category"`

	// Enclosure is a list of media files associated with the item
	Enclosure []ItemEnclosure `xml:"enclosure"`

	// Description is a synopsis of the item
	Description string `xml:"description"`

	// Author is the email address of the author of the item
	Author string `xml:"author"`

	// Content is the full content of the item (if available)
	Content string `xml:"content"`

	// FullText is the complete text content of the item
	FullText string `xml:"full-text"`
}

Item represents a single item in an RSS channel. Each item typically represents a story, article, or other piece of content.

type ItemEnclosure

type ItemEnclosure struct {
	// URL is the location of the enclosed file
	URL string `xml:"url,attr"`

	// Type is the MIME type of the enclosed file
	Type string `xml:"type,attr"`
}

ItemEnclosure represents an enclosure element in an RSS item. Enclosures are used to include media files with RSS items.

Directories

Path Synopsis
examples
context command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址