og

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 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.

Documentation

Overview

Package og generates Open Graph PNG cards on demand and caches them via a pluggable Storage so multiple pods don't redo the work.

One Generator per service produces 1200x630 PNG bytes from a (Title, Subtitle, Brand, Lang, Theme) Card. Output is deterministic — same Card → identical bytes — so a content hash of the Card doubles as the storage key. Two pods that race on first generation produce the same bytes, and Storage.PutIfAbsent keeps the write idempotent (`If-None-Match: *` on MinIO/S3, sync.Mutex for the in-memory dev store).

Two-layer wiring:

  • Generator → pure render. Pulls in golang.org/x/image fonts and `image/png`; no I/O.
  • Handler → cache-aside HTTP serving. A Resolver maps the request to a Card; on storage hit it serves bytes; on miss it renders, PutIfAbsents, then serves.

In production Storage is the MinIO-backed implementation from packages/storageclient (TBD); URLs point at the CDN in front of MinIO so the og handler is bypassed entirely on warm cards. The in-process MemoryStorage is enough for local dev and tests.

The render.Site auto-wiring (see render.Options.OG) registers the handler at /og/, exposes an `ogImage` template helper, and uses locale strings `og.<page>.title` / `og.<page>.subtitle` (with fallbacks to `site.title` / `site.description`) for content. A service that wants finer control bypasses the auto-wiring and constructs Generator + NewHandler directly.

Index

Constants

View Source
const (
	Width  = 1200
	Height = 630
)

Standard OG dimensions. Twitter, Slack, LinkedIn, WhatsApp all recommend 1200x630 — going smaller crops on retina previews, going larger gets downsized server-side anyway.

Variables

View Source
var ErrNotFound = errors.New("og: storage: not found")

ErrNotFound is what Storage.Get returns when a key has never been written. Callers compare with errors.Is — concrete impls (MinIO, in-process) wrap their underlying error so the cause is still inspectable in logs.

Functions

func NewHandler

func NewHandler(opts HandlerOptions) http.Handler

NewHandler returns the cache-aside HTTP handler:

  1. Resolve the request to a Card.
  2. Hash the Card to a key.
  3. Try Storage.Get(key) — hit serves the bytes.
  4. Miss → Generator.Render(card) → Storage.PutIfAbsent → serve the freshly-rendered bytes.

On a transient storage failure (anything other than ErrNotFound), the handler returns 500 rather than rendering blind — re-rendering on every request during an outage hides the underlying problem and burns CPU. PutIfAbsent failures after a successful render are logged as warnings and the response still goes out, so a flapping storage layer doesn't break user-visible OG previews.

Types

type Card

type Card struct {
	Title    string
	Subtitle string
	Brand    string
	Lang     string
	// Theme picks one of the named themes registered on the
	// Generator. "" (or unknown) → the "default" theme.
	Theme string
}

Card is the content of one OG image. Two Cards with identical fields produce byte-identical PNGs, so Generator.Key is a stable content hash that doubles as the storage filename.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator turns Cards into PNG bytes. Stateless w.r.t. the request — share one instance across goroutines.

func New

func New(opts Options) (*Generator, error)

New builds a Generator with the default theme always available under the name "default", plus any extras passed in Options.Themes.

func (*Generator) Key

func (g *Generator) Key(c Card) string

Key returns a 16-hex-char SHA-256 prefix of the Card. Same Card → same Key, so it's safe to use as the storage filename and as the cache-buster in URLs (callers shouldn't see the hash collide across distinct cards within the lifetime of a deployment).

Theme name is part of the hash — changing palette without renaming the theme silently won't invalidate cached cards. Bump the theme name (or keep a version suffix in the name) when the visual changes.

func (*Generator) Render

func (g *Generator) Render(c Card) ([]byte, error)

Render produces the PNG bytes for c. The output is deterministic per (Card, theme) — caller can hash the result or use Key for the same hash without ever rendering.

type HandlerOptions

type HandlerOptions struct {
	Generator *Generator
	Storage   Storage

	// Resolver maps an http.Request to the Card it represents.
	// Returning (_, false) makes the handler reply 404 — use that
	// for unknown locales, missing pages, or paths that don't match
	// the expected scheme. The Resolver is the only thing the
	// handler needs from outside, so a service can use any URL
	// scheme it likes (lang/page paths, opaque hashes, query
	// params) by writing one function.
	Resolver func(*http.Request) (Card, bool)
}

HandlerOptions configures NewHandler.

type MemoryStorage

type MemoryStorage struct {
	// contains filtered or unexported fields
}

MemoryStorage is the in-process Storage implementation: a map guarded by a RWMutex, with URLs that point at the bundled HTTP handler. Suitable for local dev and unit tests; do not use in prod (cards regenerate on every restart and don't sync between pods).

func NewMemoryStorage

func NewMemoryStorage(urlPrefix string) *MemoryStorage

NewMemoryStorage builds an empty store. urlPrefix is the path the service mounts the OG handler under (e.g. "/og"); URL appends "/<key>.png" so the same NewHandler reads back what was written. Trailing slashes are tolerated.

func (*MemoryStorage) Get

func (m *MemoryStorage) Get(_ context.Context, key string) ([]byte, string, error)

Get returns the stored bytes + contentType, or ErrNotFound.

func (*MemoryStorage) PutIfAbsent

func (m *MemoryStorage) PutIfAbsent(_ context.Context, key string, body []byte, contentType string) error

PutIfAbsent stores body under key when no value exists; on duplicate keys it returns nil silently (consistent with how the MinIO impl will handle the 412 from `If-None-Match: *`). Caller owns body before the call; we keep our own copy so a later mutation of the input slice doesn't corrupt the cache.

func (*MemoryStorage) URL

func (m *MemoryStorage) URL(key string) string

URL returns "<URLPrefix>/<key>.png".

func (*MemoryStorage) URLPrefix

func (m *MemoryStorage) URLPrefix() string

URLPrefix is the prefix passed to NewMemoryStorage with any trailing slash trimmed. Exposed so the auto-mount in render.Site can derive the route path from the same source of truth.

type Options

type Options struct {
	// Themes registers extra themes alongside the implicit "default"
	// theme. nil → just the default. A theme set with name "default"
	// here overrides the built-in palette.
	Themes map[string]Theme
}

Options configures a Generator at boot.

type Storage

type Storage interface {
	// Get returns the bytes stored at key. Returns ErrNotFound when
	// the key has never been written; any other error is a real
	// storage failure (network, auth, quota) and the handler treats
	// it as a 500 rather than re-rendering — re-rendering on a
	// transient outage would just paper over the problem.
	Get(ctx context.Context, key string) ([]byte, string, error)

	// PutIfAbsent stores body+contentType at key only if no object
	// exists there. The second of two concurrent writes returns
	// nil (idempotent) — both wrote identical bytes anyway. A
	// non-nil error indicates a real failure, not a race.
	PutIfAbsent(ctx context.Context, key string, body []byte, contentType string) error

	// URL returns a public URL for key. For MinIO behind a CDN
	// this is the cdn.example.com URL pages embed in og:image
	// meta tags directly; for MemoryStorage it's the relative path
	// served by the bundled handler.
	URL(key string) string
}

Storage is the put-once / read-by-key contract OG needs from a blob store. Two pods rendering the same Card race-write the same bytes; PutIfAbsent makes that idempotent so neither pod overwrites the other's identical content. Implementations:

  • MemoryStorage (this file) — in-process map, suitable for local dev and tests.
  • MinIO/S3 (in packages/storageclient, when it lands) — uses `If-None-Match: *` on the PUT so the second writer in a race gets a 412 the impl swallows.

type Theme

type Theme struct {
	Background    color.Color
	BrandColor    color.Color
	TitleColor    color.Color
	SubtitleColor color.Color
	AccentColor   color.Color

	BrandFace    font.Face
	TitleFace    font.Face
	SubtitleFace font.Face

	PaddingX int
	PaddingY int

	TitleLineGap     int // extra space between wrapped title lines
	SubtitleLineGap  int // extra space between wrapped subtitle lines
	TitleSubtitleGap int // gap between the title block and the subtitle block

	AccentBar int // bottom accent strip height; 0 = none
}

Theme is the visual style of an OG card. Values are concrete (not pointers) so a Theme is safe to copy into the Generator's map; the font.Faces inside are also goroutine-safe by design.

Sizes are integer pixel offsets so the renderer can stay in integer math throughout. PaddingX/PaddingY are uniform inner margins; AccentBar is the height of the bottom band (set to 0 to disable).

func DefaultTheme

func DefaultTheme() (Theme, error)

DefaultTheme returns the built-in palette: deep navy background, warm-orange brand mark, white title, muted-grey subtitle, orange accent strip at the bottom. Uses the Go fonts (gobold + goregular) so the binary stays self-contained — no font asset to embed.

Tweak the colours and font sizes here when the design system lands; services that want a different look register their own Theme via Options.Themes and pass the name through Card.Theme.

Jump to

Keyboard shortcuts

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