Sell ebooks, templates, software and other files: private storage, entitlements granted when an order is paid, download links with expiry and download limits, short-lived signed URLs, revocation on refund and link resends, in Go with Encore.

Selling files looks simpler than shipping physical goods until the first customer forwards their download link to a forum. A digital downloads backend has to tie each file to a paid order, keep links working long enough for a customer on a slow connection, and stop them from becoming free public mirrors.
This guide builds that backend in Go: private storage, entitlements from order events, expiring and counted links, and revocation on refund.
Use two links with different lifetimes: the link in the order email points at your API and contains a random token, valid for something like 30 days and 5 downloads. The URL the customer's browser finally fetches is a signed URL for the object, generated per download and valid for a few minutes.
A signed storage URL cannot be revoked once issued, so keeping it short-lived limits what a leak can do, while the API link stays revocable and countable because every use goes through your database. Store only a hash of the token, the same way you would store a password reset token, so a database dump does not hand out working links.
Grant entitlements from the payment provider's confirmed event, not from the redirect after checkout. Stripe's fulfillment guide, for example, recommends fulfilling from webhooks, since a customer can close the tab before the success page loads. In this guide, the orders service turns that webhook into an OrderPaid event.
Encore is a backend framework with built-in infrastructure, so the private bucket, the entitlements database and the order event subscriptions are declarations in the downloads service, and Encore creates them in your own AWS or GCP account on deploy. Groupon reports a 3x increase in development speed and 90% shorter project lead times.

Run in your terminal to get started locally.
The schema keeps one entitlement per order and product, which is what makes the subscriber safe to run twice:
-- downloads/migrations/1_init.up.sql
CREATE TABLE products (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
object_key TEXT NOT NULL,
download_limit INT NOT NULL DEFAULT 5
);
CREATE TABLE entitlements (
id BIGSERIAL PRIMARY KEY,
order_id TEXT NOT NULL,
product_id TEXT NOT NULL REFERENCES products (id),
customer_email TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
downloads INT NOT NULL DEFAULT 0,
max_downloads INT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (order_id, product_id)
);
The orders service publishes when payment is confirmed and when a refund goes through, on topics any service can subscribe to:
// orders/events.go
package orders
import "encore.dev/pubsub"
type OrderPaid struct {
OrderID string `json:"order_id"`
Email string `json:"email"`
ProductIDs []string `json:"product_ids"`
}
type OrderRefunded struct {
OrderID string `json:"order_id"`
}
var Paid = pubsub.NewTopic[*OrderPaid]("order-paid", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
var Refunded = pubsub.NewTopic[*OrderRefunded]("order-refunded", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
The downloads service declares a private bucket and grants an entitlement per product. ON CONFLICT DO NOTHING turns a redelivered event into a no-op, and the email only goes out for rows that were inserted:
// downloads/grants.go
package downloads
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"time"
"encore.app/orders"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/objects"
"encore.dev/storage/sqldb"
)
// Private by default: no public URLs, access only through signed URLs.
var files = objects.NewBucket("product-files", objects.BucketConfig{})
var db = sqldb.NewDatabase("downloads", sqldb.DatabaseConfig{
Migrations: "./migrations",
})
const linkLifetime = 30 * 24 * time.Hour
func newToken() (token, hash string) {
b := make([]byte, 32)
rand.Read(b)
token = hex.EncodeToString(b)
sum := sha256.Sum256([]byte(token))
return token, hex.EncodeToString(sum[:])
}
var _ = pubsub.NewSubscription(orders.Paid, "grant-downloads", pubsub.SubscriptionConfig[*orders.OrderPaid]{
Handler: grant,
})
func grant(ctx context.Context, e *orders.OrderPaid) error {
for _, productID := range e.ProductIDs {
token, hash := newToken()
var id int64
err := db.QueryRow(ctx, `
INSERT INTO entitlements (order_id, product_id, customer_email, token_hash, max_downloads, expires_at)
SELECT $1, p.id, $3, $4, p.download_limit, now() + $5 * interval '1 second'
FROM products p WHERE p.id = $2
ON CONFLICT (order_id, product_id) DO NOTHING
RETURNING id`,
e.OrderID, productID, e.Email, hash, int64(linkLifetime.Seconds()),
).Scan(&id)
if errors.Is(err, sqldb.ErrNoRows) {
continue // already granted, or unknown product
}
if err != nil {
return err
}
if err := sendDownloadEmail(ctx, e.Email, "https://shop.example.com/dl/"+token); err != nil {
return err
}
}
return nil
}
var _ = pubsub.NewSubscription(orders.Refunded, "revoke-downloads", pubsub.SubscriptionConfig[*orders.OrderRefunded]{
Handler: func(ctx context.Context, e *orders.OrderRefunded) error {
_, err := db.Exec(ctx, `
UPDATE entitlements SET revoked_at = now()
WHERE order_id = $1 AND revoked_at IS NULL`, e.OrderID)
return err
},
})
// sendDownloadEmail hands the link to your email provider.
func sendDownloadEmail(ctx context.Context, to, link string) error {
rlog.Info("download link issued", "to", to)
return nil
}
If the email call fails, the subscriber returns the error and the event is retried, but the row already exists and the retry skips it. The resend endpoint below covers that case and the common "I lost the email" ticket by rotating the token, which also invalidates the old link.
The download endpoint is a raw endpoint so it can answer with a redirect. One UPDATE checks expiry, revocation and the limit and increments the count, so two parallel requests cannot both use the last download:
// downloads/serve.go
package downloads
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"time"
"encore.dev"
"encore.dev/storage/objects"
"encore.dev/storage/sqldb"
)
//encore:api public raw method=GET path=/dl/:token
func Download(w http.ResponseWriter, req *http.Request) {
token := encore.CurrentRequest().PathParams.Get("token")
sum := sha256.Sum256([]byte(token))
var objectKey string
err := db.QueryRow(req.Context(), `
UPDATE entitlements e SET downloads = e.downloads + 1
FROM products p
WHERE e.token_hash = $1 AND p.id = e.product_id
AND e.revoked_at IS NULL AND e.expires_at > now()
AND e.downloads < e.max_downloads
RETURNING p.object_key`, hex.EncodeToString(sum[:]),
).Scan(&objectKey)
if errors.Is(err, sqldb.ErrNoRows) {
http.Error(w, "This download link has expired or reached its limit.", http.StatusGone)
return
}
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
signed, err := files.SignedDownloadURL(req.Context(), objectKey, objects.WithTTL(5*time.Minute))
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
http.Redirect(w, req, signed.URL, http.StatusFound)
}
type ResendParams struct {
OrderID string `json:"order_id"`
Email string `json:"email"`
}
// Resend rotates the token for every active entitlement on the order and emails new links.
//
//encore:api public method=POST path=/downloads/resend
func Resend(ctx context.Context, p *ResendParams) error {
rows, err := db.Query(ctx, `
SELECT id FROM entitlements
WHERE order_id = $1 AND customer_email = $2
AND revoked_at IS NULL AND expires_at > now()`, p.OrderID, p.Email)
if err != nil {
return err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
rows.Close()
for _, id := range ids {
token, hash := newToken()
if _, err := db.Exec(ctx, `UPDATE entitlements SET token_hash = $1 WHERE id = $2`, hash, id); err != nil {
return err
}
if err := sendDownloadEmail(ctx, p.Email, "https://shop.example.com/dl/"+token); err != nil {
return err
}
}
return nil
}
Resend returns the same empty response whether or not the order and email match, so it cannot be used to probe which emails bought what, and it only sends to the address already on the order. Name objects with the file name the customer should see, such as products/field-guide/field-guide.pdf, since that becomes the default download name unless a Content-Disposition header sets another.
Uploading product files goes through files.SignedUploadURL from your admin tooling, so large files go straight to the bucket instead of through the API.
encore run starts Postgres, Pub/Sub and a local bucket, so a test can publish an OrderPaid event, follow the link from the log line and check that the sixth download returns 410. On deploy to your AWS or GCP account, the bucket becomes a private S3 or Cloud Storage bucket, the database becomes RDS or Cloud SQL, and the topics become SNS with SQS or Google Pub/Sub, as described in the infrastructure docs.
Adding a new rule, such as a per-product expiry, is a migration and a change to one query, and a coding agent can make both in the same diff and test it against the local database before it ships, as covered in the database docs.
Best fit: ecommerce teams selling files, templates or software who want paid orders turned into counted, revocable downloads from storage in their own AWS or GCP account.
Keep the files in a private bucket and never expose its URLs. When the order is paid, create an entitlement with a random token, an expiry and a download limit, email a link containing the token, and have the download endpoint check and count the entitlement before redirecting to a signed URL that expires within minutes.
Separate the two links. The link in the email can stay valid for days or weeks with a limit of a few downloads, while the signed storage URL it redirects to should expire within minutes, so a shared or leaked storage URL stops working almost immediately.
Store a download count and a maximum on the entitlement, and increment the count in the same UPDATE that checks it, with a condition like downloads < max_downloads. A single atomic statement keeps two parallel requests from both getting through on the last remaining download.
Declare a private bucket with objects.NewBucket, a database with sqldb.NewDatabase and a subscription to your order-paid topic. The subscriber creates entitlements, and a raw endpoint checks the token, increments the count and redirects to bucket.SignedDownloadURL with objects.WithTTL(5 * time.Minute).
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.