ogimage

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 26 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.

README

Generate OG images for your Laravel Go app

Latest version Tests Go Reference

Define Open Graph images as HTML in your Laravel Go views. The package generates screenshots, serves them through a dedicated route, and caches them on disk. Templates inherit your page's existing CSS, fonts and assets.

Support us

Support Spatie's open source work

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

Requires Go 1.27 or newer and Laravel Go go.laravel.com v0.1.0.

go get github.com/spatie/laravel-og-image-go@v0.1.1

Install the package explicitly in bootstrap/app.go:

import (
    ogimage "github.com/spatie/laravel-og-image-go"
    laravel "go.laravel.com"
)

func Options() laravel.Options {
    return laravel.Options{
        Packages: []laravel.Package{ogimage.New()},
    }
}

The default driver uses Browsershot Go and requires Node.js, Puppeteer and Chrome/Chromium. You can use Cloudflare Browser Rendering or a custom driver instead.

Usage

<template data-og-image>
    <div class="w-full h-full bg-blue-900 text-white flex items-center justify-center">
        <h1 class="text-6xl font-bold">{{.Title}}</h1>
    </div>
</template>

The web middleware injects og:image, twitter:image, and twitter:card tags into the page's <head>. The image is generated on its first request at 1200×630 CSS pixels with 2× scale. Later requests serve the stored file. Append ?ogimage to preview a page's image.

Configure dimensions, format, quality, storage, fallbacks, screenshot options, URL resolution and action replacements through ogimage.New(func(c *ogimage.Config) { ... }). Use ogimage.From(ctx).GenerateForURL(ctx, pageURL) or laravel og-image:generate <urls> to pre-generate trusted page URLs. Use laravel og-image:clear to remove generated images.

The default URL resolver uses the configured application origin, preserves escaped path segments such as %2F, and drops query parameters. Supply Config.ResolveURL when image content depends on the query string.

See the documentation.

Testing

go test -race ./...

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details. Coding agents should read AGENTS.md and load the relevant skills in .agents/skills/.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Documentation

Overview

Package ogimage generates Open Graph images from Laravel Go page templates.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("ogimage: image metadata not found")

ErrNotFound means the filename is invalid or its page metadata is absent.

Functions

func HTML

func HTML(content string, options ...Options) (template.HTML, error)

HTML wraps already-rendered, trusted application HTML in an inert template. Escape untrusted text before passing it. The output is never compiled again.

func Hash

func Hash(content string, options Options) string

Hash matches the PHP content hash, including dimensions only when overridden. It identifies content, not authentication or authorization.

func ImageURL

func ImageURL(value string) (template.HTML, error)

ImageURL uses an existing image without generating or caching a screenshot.

Types

type Actions

type Actions struct {
	Generate         func(*web.Request, *Service, string) *web.Response
	InjectFallback   func(*web.Request, *Service, string) (string, error)
	RenderScreenshot func(context.Context, *Service, string) (string, error)
}

Actions replace PHP's generate, fallback injection and screenshot rendering actions. The Default methods on Service can be called to decorate the built-in behavior.

type BrowsershotDriver

type BrowsershotDriver struct {
	Configure func(*browsershot.Browsershot)
}

BrowsershotDriver captures the live page preview with Node, Puppeteer and Chrome. Configure receives a fresh builder for each capture, after shared options apply.

func (BrowsershotDriver) Capture

func (d BrowsershotDriver) Capture(ctx context.Context, s Screenshot) ([]byte, error)

type ClearCommand

type ClearCommand struct{}

ClearCommand deletes files directly in the configured image directory.

func (*ClearCommand) Description

func (*ClearCommand) Description() string

func (*ClearCommand) Name

func (*ClearCommand) Name() string

func (*ClearCommand) Run

type CloudflareDriver

type CloudflareDriver struct {
	APIToken  string
	AccountID string
}

CloudflareDriver uses Cloudflare Browser Rendering without a local Chrome installation.

func (CloudflareDriver) Capture

func (d CloudflareDriver) Capture(ctx context.Context, s Screenshot) ([]byte, error)

type Config

type Config struct {
	BaseURL          string
	Disk             string
	Path             string
	Width            int
	Height           int
	Format           string
	Quality          int
	PreviewParameter string
	MaxAge           time.Duration
	MetadataTTL      time.Duration
	LockTimeout      time.Duration
	// RemoteDisk redirects image requests to the disk's public URL.
	RemoteDisk          bool
	Driver              Driver
	ConfigureScreenshot func(*Screenshot)
	Fallback            func(*web.Request) (string, error)
	ResolveURL          func(*web.Request) (string, error)
	Actions             Actions
}

Config configures one application. Callbacks must be safe for concurrent use.

type Driver

type Driver interface {
	Capture(context.Context, Screenshot) ([]byte, error)
}

Driver takes a screenshot and returns encoded image bytes. Implementations must honor context cancellation and be safe for concurrent calls.

type DriverFunc

type DriverFunc func(context.Context, Screenshot) ([]byte, error)

DriverFunc adapts a function to a custom screenshot driver.

func (DriverFunc) Capture

func (f DriverFunc) Capture(ctx context.Context, s Screenshot) ([]byte, error)

type GenerateCommand

type GenerateCommand struct{}

GenerateCommand pre-generates each trusted URL and continues after individual failures.

func (*GenerateCommand) Arguments

func (*GenerateCommand) Arguments() []laravel.Argument

func (*GenerateCommand) Description

func (*GenerateCommand) Description() string

func (*GenerateCommand) Name

func (*GenerateCommand) Name() string

func (*GenerateCommand) Run

type Metadata

type Metadata struct {
	URL    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

Metadata is cached for Config.MetadataTTL unless cleared or evicted earlier.

type Options

type Options struct {
	Width, Height int
	Format        string
}

Options override a template's format or dimensions. Set both dimensions or neither.

type Package

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

Package installs routes, web middleware, views and console commands.

func New

func New(configure ...func(*Config)) *Package

New applies code configuration after environment defaults at registration time.

func (*Package) Register

func (p *Package) Register(app *laravel.Registrar) error

Register creates fresh, application-scoped state on each registration.

type Render

type Render struct{}

Render processes successful buffered HTML web responses, leaving streams and JSON untouched.

func (Render) Handle

func (Render) Handle(r *web.Request, next web.Next) *web.Response

type Screenshot

type Screenshot struct {
	URL           string
	Width, Height int
	Format        string
	Quality       int
	Scale         float64
	WaitUntil     string
	Delay         time.Duration
}

Screenshot contains the resolved options after ConfigureScreenshot runs.

type ScreenshotLayout

type ScreenshotLayout struct {
	Head, Content template.HTML
	Width, Height int
}

ScreenshotLayout is passed to the overridable og-image::screenshot view.

type Service

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

Service is immutable after registration and safe for concurrent requests.

func From

func From(ctx context.Context) *Service

From returns the service installed in the context's application.

func (*Service) DefaultInjectFallback

func (s *Service) DefaultInjectFallback(r *web.Request, source string) (string, error)

DefaultInjectFallback adds a fallback template only when a body closing tag exists.

func (*Service) DefaultRenderScreenshot

func (s *Service) DefaultRenderScreenshot(ctx context.Context, source string) (string, error)

DefaultRenderScreenshot preserves the page's head and renders only template content.

func (*Service) DefaultResponse

func (s *Service) DefaultResponse(r *web.Request, filename string) *web.Response

DefaultResponse generates missing images under a shared cache lock and serves them.

func (*Service) Generate

func (s *Service) Generate(ctx context.Context, filename string) error

Generate captures a known image once. Unknown names never trigger browser navigation.

func (*Service) GenerateForURL

func (s *Service) GenerateForURL(ctx context.Context, pageURL string, format ...string) (string, error)

GenerateForURL fetches a trusted page and pre-generates its image. Never pass arbitrary visitor input. Fetching pages and browser navigation can reach private networks.

func (*Service) Metadata

func (s *Service) Metadata(ctx context.Context, hash string) (Metadata, bool, error)

Metadata retrieves the page URL and optional per-template dimensions.

func (*Service) Prepare

func (s *Service) Prepare(r *web.Request, source string) (string, error)

Prepare injects social tags and caches the page URL, or renders preview HTML. Only pass successful HTML page responses, never JSON, files or streams.

func (*Service) Response

func (s *Service) Response(r *web.Request) *web.Response

Response serves a validated filename using the configured generation action.

func (*Service) StoreMetadata

func (s *Service) StoreMetadata(ctx context.Context, hash string, metadata Metadata) error

StoreMetadata remembers the first page for content, without replacing earlier metadata.

func (*Service) URL

func (s *Service) URL(hash, format string) string

URL returns the stable application endpoint, not a storage URL.

Jump to

Keyboard shortcuts

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