RSS'den 66 sosyal ağa: Facebook, Instagram, X, LinkedIn, Telegram ve daha fazlası Blog Satış Ortaklığı İletişim
Giriş yapın Ücretsiz başlayın
Updated: 2026-10-23
Gin RSS Feed in Go: Handler, Dates and Conditional GET

Short answer: To serve an RSS feed from a Gin application, register a GET route for /feed.xml, query the newest published rows with database/sql, describe the channel and its items with structs from the encoding/xml package so every value is escaped, format dates in UTC with a fixed RFC 822 layout, and send the bytes with the application/rss+xml content type. Compute an ETag from the finished body and answer a matching If-None-Match header with a 304, take the last build date from the newest item so the body stays identical between changes, test the route with curl and a validator, then give the public address to an auto-poster.

Gin is one of the most popular web frameworks for Go. It is fast, small and easy to read, and teams use it for APIs, internal dashboards and content services that run as a single static binary. Sooner or later such a service publishes something that people want to follow: articles, release notes, offers, events or listings. A feed is the standard way to let readers, aggregators and auto-posters watch that content without an account or an API key. Go has no feed library in its standard package set, but it does not need one, because the XML encoder is part of the language. This guide builds a complete Gin RSS feed with a clean query, stable identifiers, correct dates and conditional requests, explains each decision and ends with the checks that keep the feed dependable once other systems rely on it.

When a Gin service needs a feed

A feed is worth adding whenever the service publishes things that people outside it want to follow:

  • articles, news or announcements stored in a database and served by the application;
  • release notes or a changelog for a product, a library or an internal tool;
  • listings, events, offers or openings added by staff or by users;
  • any content that should also appear on social networks without being copied by hand.

If your content already lives in a blog or a CMS, use the feed it provides instead; see how to find your WordPress feed link. If you prefer a feed library, the gorilla feeds guide shows the same job done with a package; only the way the XML is produced changes.

Set up the project

Create a module and fetch the two dependencies. The example uses an embedded SQLite driver written in Go so that it runs anywhere without a C compiler, but the query and the loop stay the same with PostgreSQL or MySQL and their drivers.

go mod init example.com/newsfeed
go get github.com/gin-gonic/gin
go get modernc.org/sqlite

Keep the public address of the site in configuration rather than reading it from the incoming request. Behind a reverse proxy the request may show an internal host name or a plain http scheme, and a feed full of internal addresses is useless to every reader. The example reads the address from an environment variable with a safe default.

The complete handler

The program below defines the shape of the document as structs, loads the newest rows, builds the XML once per request and sends it with a strong validator. The condition on the publication time matters: without it, an item scheduled for tomorrow would appear in the feed today, and an auto-poster would share it before it exists on the website. Publication times are stored as UTC unix timestamps.

package main

import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"encoding/xml"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	_ "modernc.org/sqlite"
)

const rfc822 = "Mon, 02 Jan 2006 15:04:05 GMT"

type AtomLink struct {
	Href string `xml:"href,attr"`
	Rel  string `xml:"rel,attr"`
	Type string `xml:"type,attr"`
}

type GUID struct {
	IsPermaLink string `xml:"isPermaLink,attr"`
	Value       string `xml:",chardata"`
}

type Item struct {
	Title       string `xml:"title"`
	Link        string `xml:"link"`
	GUID        GUID   `xml:"guid"`
	PubDate     string `xml:"pubDate"`
	Description string `xml:"description"`
}

type Channel struct {
	Title         string   `xml:"title"`
	Link          string   `xml:"link"`
	Description   string   `xml:"description"`
	Language      string   `xml:"language"`
	LastBuildDate string   `xml:"lastBuildDate"`
	Self          AtomLink `xml:"atom:link"`
	Items         []Item   `xml:"item"`
}

type Rss struct {
	XMLName xml.Name `xml:"rss"`
	Version string   `xml:"version,attr"`
	Atom    string   `xml:"xmlns:atom,attr"`
	Channel Channel  `xml:"channel"`
}

func loadItems(ctx context.Context, db *sql.DB, site string) ([]Item, int64, error) {
	rows, err := db.QueryContext(ctx,
		"SELECT id, title, slug, summary, published_at FROM posts "+
			"WHERE status = 'published' AND published_at <= ? "+
			"ORDER BY published_at DESC LIMIT 20", time.Now().Unix())
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()

	var items []Item
	var newest int64
	for rows.Next() {
		var id, published int64
		var title, slug, summary string
		if err := rows.Scan(&id, &title, &slug, &summary, &published); err != nil {
			return nil, 0, err
		}
		if newest == 0 {
			newest = published
		}
		items = append(items, Item{
			Title:       title,
			Link:        site + "/" + slug + "/",
			GUID:        GUID{IsPermaLink: "false", Value: "post-" + strconv.FormatInt(id, 10)},
			PubDate:     time.Unix(published, 0).UTC().Format(rfc822),
			Description: summary,
		})
	}
	return items, newest, rows.Err()
}

func main() {
	site := os.Getenv("SITE_URL")
	if site == "" {
		site = "https://www.example.com"
	}
	db, err := sql.Open("sqlite", "data/site.db")
	if err != nil {
		panic(err)
	}

	r := gin.Default()
	r.GET("/feed.xml", func(c *gin.Context) {
		items, newest, err := loadItems(c.Request.Context(), db, site)
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		feed := Rss{
			Version: "2.0",
			Atom:    "http://www.w3.org/2005/Atom",
			Channel: Channel{
				Title:         "Example News",
				Link:          site + "/",
				Description:   "The latest posts from Example News",
				Language:      "en",
				LastBuildDate: time.Unix(newest, 0).UTC().Format(rfc822),
				Self:          AtomLink{Href: site + "/feed.xml", Rel: "self", Type: "application/rss+xml"},
				Items:         items,
			},
		}
		body, err := xml.MarshalIndent(feed, "", "  ")
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		body = append([]byte(xml.Header), body...)

		sum := sha256.Sum256(body)
		etag := `"` + hex.EncodeToString(sum[:8]) + `"`
		c.Header("ETag", etag)
		c.Header("Cache-Control", "public, max-age=300")
		if c.GetHeader("If-None-Match") == etag {
			c.AbortWithStatus(http.StatusNotModified)
			return
		}
		c.Data(http.StatusOK, "application/rss+xml; charset=utf-8", body)
	})
	r.Run(":8080")
}

Run it with go run and open the route in a browser or with curl. You should see well-formed XML with at most twenty items, newest first. The query receives the context of the request, so a client that disconnects does not leave a query running. Each value is escaped by the encoder, so a title containing an ampersand or an angle bracket cannot break the document.

How the ETag logic works

Gin does not add validators on its own, so the handler builds one. It hashes the finished body, keeps the first eight bytes as a short hexadecimal string, wraps it in quotation marks as the HTTP specification requires and compares it with the If-None-Match header of the request. A match means the client already holds exactly these bytes, so the handler sends a 304 with no body. A poll that finds nothing new then costs one query and a few hundred bytes of headers.

The hash is computed from the body, which brings one rule: the body must not change unless the content changes. That is why the example takes the last build date from the newest item and not from the clock. If you wrote the current time there, the hash would change on every request, the ETag would never match and the 304 answer would never be sent. The same rule applies to any generator that stamps the current time into its output, in any language. The background to this technique is in the guide to ETags and conditional GET.

Where each field comes from

Feed fieldSource in the exampleRule to keep
titleThe title columnPlain text, escaped by the encoder
linkSite address plus slugAbsolute address that returns 200 directly
guidThe row id with a prefixNever changes, even if the slug changes
pubDateThe publication timestamp in UTCRFC 822 layout with GMT, never in the future
descriptionThe summary columnOne or two sentences that make sense alone
lastBuildDateThe newest publication timestampChanges only when the content changes

The identifier is the most important decision. An auto-poster remembers which items it has already shared by their GUID. If the value changes when someone edits a slug or republishes an article, the same story is shared again. Using the database id with a fixed prefix, and marking it as not a permanent link, avoids that. The problem and its fixes are described in why a feed auto-posts the same article twice.

Dates in the right format

RSS dates follow RFC 822, with English abbreviations for days and months. Go formats times with a reference layout, and the constant in the example spells that layout out with the literal text GMT as the zone, which every parser accepts. The value must be converted to UTC first, which is why every call in the example ends with UTC before Format. Do not use ISO 8601 in an RSS document; that format belongs to Atom feeds, and many RSS readers reject it. Be careful with the standard RFC1123 constants as well: one of them writes the zone name of the server, which can produce values some readers cannot parse. If a validator complains about dates, read the guide to RSS date format errors.

Caching without delaying new posts

Auto-posters, readers and search engines request a feed often, and almost always nothing has changed. The Cache-Control header in the example allows shared caches to keep the response for five minutes, and the ETag lets everything else end in a 304. Choose the period with care: a long one delays every new post by the same amount, because caches keep serving the old list until it expires. A few minutes is a good balance for most sites. If the table grows large, add an index on the status and publication columns so that the query stays fast. More on this trade-off is in the guide to feed caching.

Running Gin in production

Set the mode to release with the GIN_MODE environment variable so that debug output is switched off, and build the binary with go build. Put a reverse proxy in front of it that terminates HTTPS, and tell Gin which proxies to trust so that client addresses in the logs are correct. Keep the public address in your own setting rather than trusting forwarded headers, so that links in the feed are always correct. Check that the proxy does not strip the ETag and Cache-Control headers and that it does not add its own long cache that keeps old XML for too long. After every deployment, request the feed once to confirm that it still returns 200 and that the address is exactly the one you gave to the auto-poster. If the feed ever stops updating, this checklist shows what to inspect first.

Images and richer items

An auto-poster is more useful when each item carries a picture. Add an enclosure element to the item struct with the address, the length in bytes and the type of the image as attributes, and fill it from an image column. Use an absolute https address and a file of reasonable size. Without an image, many networks show a plain text card. How tools read these elements is explained in the guide to enclosure tags. If you want HTML inside the description, read the CDATA guide first.

Test the feed before you connect it

  1. Request the route with curl and look at the headers: the status should be 200, the content type should be application/rss+xml and an Etag header should be present.
  2. Repeat the request with that value in an If-None-Match header and confirm that a 304 comes back.
  3. Paste the public address into the W3C Feed Validation Service and fix every error.
  4. Insert a test row and check that it appears at the top of the feed on the next request.
  5. Set a publication time in the future and check that the item stays hidden until then.

There is a longer checklist in the feed validation guide and a short curl routine in the guide to debugging a feed with curl.

Common mistakes to avoid

  • Letting the build date follow the clock. Derive it from the newest item so that the ETag can match.
  • Future items. Filter by publication time so scheduled content stays hidden until its moment.
  • Unstable GUIDs. Use an identifier that never changes.
  • Building XML from strings. Concatenated text breaks on the first ampersand; use the encoder.
  • Addresses taken from the request. Build links from the configured public address.
  • Changing the feed address. Keep the route, or redirect the old one permanently.

How PostRSS works with a Gin feed

PostRSS has been publishing RSS and Atom feeds to social networks since 2014. Paste the address of your feed route, connect your accounts and choose how each post is built from the title, the description or the page title. PostRSS checks the feed as often as every minute and shares each new item, with its image and link, to the channels you choose among 66 supported networks, messengers, team chats and blogs, including LinkedIn, X, Bluesky, Mastodon and Telegram. Keyword filters, UTM parameters and posting windows let you tune each channel, and webhooks connect PostRSS to your own systems. See the PostRSS features page and the plan limits on the pricing page. More developer guides are under the Technical Guide tag.

İlgili Okumalar

The bottom line

Gin needs only a route, a context-aware query and the standard encoder to serve a dependable RSS feed: select published items dated in the past, let the encoder escape every value, use a stable GUID, format dates in UTC with a fixed layout, derive the last build date from the newest item and send the result with the right content type. Add a hash-based ETag so repeat requests end in a 304. Test the route with curl and a validator, keep the address unchanged and connect it to an auto-poster. After that, every item you publish can reach your social channels automatically.

FAQ

Does Gin have a built-in RSS generator?

No. Gin has no feed support, but the encoding/xml package in the Go standard library produces a valid RSS document from a few structs, and the route returns it with the right content type.

Do I need to write ETag code in Gin?

Yes, for a conditional response. Gin does not compute validators by itself, so the handler hashes the body, sets the ETag header and returns 304 when the request carries a matching If-None-Match value.

Why does my feed never return 304?

Most often the body changes between requests, for example because the last build date is the current time. Take that date from the newest item and the hash stays the same until the content changes.

How many items should the feed contain?

Between ten and twenty of the newest published items is enough. An auto-poster only needs recent items, and a smaller file is faster to download and parse.

Can I use this feed with PostRSS?

Yes. PostRSS reads any valid RSS or Atom address that is reachable without a login. Paste the address, connect your channels and new items are shared as soon as they appear.

New guides, once a month

What changed in the networks, what broke, and how to fix it before it costs you reach.

We send a confirmation e-mail first. Unsubscribe any time.

Ekibimizden daha fazla araç

PostRSS'in arkasındaki ekip Internet Solutions tarafından geliştirildi. Her biri size farklı bir şekilde zaman kazandırır.