plugin

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package plugin defines the interface for goblog plugins. Plugins can inject data into templates, add HTML to <head> and <body>, register scheduled background jobs, and define their own settings.

Plugins can be compiled-in (imported and registered in main()) or loaded dynamically from .go files in the plugins/ directory at startup.

Index

Constants

View Source
const (
	MaxStoreKeyBytes   = 256
	MaxStoreValueBytes = 1 << 20
	// MaxStorePluginBytes and MaxStorePluginRows cap what one plugin may keep
	// in total, so a runaway plugin cannot fill the database.
	MaxStorePluginBytes = 16 << 20
	MaxStorePluginRows  = 10000
)
View Source
const MaxPostsList = 50

MaxPostsList caps how many posts one posts_list call returns.

Variables

View Source
var ErrStoreUnavailable = errors.New("plugin store: database not ready")

ErrStoreUnavailable is returned before the database is configured (wizard).

View Source
var Symbols = map[string]map[string]reflect.Value{
	"github.com/goblogplatform/goblog/plugin/plugin": symbols,
	"goblog/plugin/plugin":                           symbols,
}

Symbols exports the plugin package types to the Yaegi interpreter so dynamic plugins can `import "goblog/plugin"` and use plugin.BasePlugin, plugin.HookContext, etc. Yaegi keys symbol maps as "<import path>/<package name>", the same way its stdlib does ("fmt/fmt").

The _Plugin entry and the _goblog_plugin_Plugin wrapper below are what let an interpreted type satisfy the compiled Plugin interface; they follow the shape `yaegi extract` generates. Registry internals are deliberately not exported: a plugin only needs the types it implements or receives.

Yaegi finds the _Plugin wrapper under the type's real package path, so the symbols are keyed by the module path; "goblog/plugin" is kept as an alias because that is the import existing dynamic plugins use.

Functions

func LoadDynamicPlugins

func LoadDynamicPlugins(registry *Registry, dir string)

LoadDynamicPlugins scans a directory for .go plugin files and loads them using the Yaegi Go interpreter. Each file must use `package main` and define a function:

func NewPlugin() plugin.Plugin

The returned plugins are registered with the given registry.

func Middleware

func Middleware(registry *Registry) gin.HandlerFunc

Middleware returns a Gin middleware that stores the registry on the context.

func PageSlug

func PageSlug(db *gorm.DB, pageType, def string) string

PageSlug is the slug of the page with pageType as the admin has it (a plugin page can be renamed in Admin → Pages), or def when the row is missing or db is nil. Plugins use it to link to their own pages from somewhere other than the page itself, such as a search result.

Types

type BasePlugin

type BasePlugin struct{}

BasePlugin provides no-op implementations of all Plugin methods.

func (BasePlugin) OnInit

func (BasePlugin) OnInit(db *gorm.DB) error

func (BasePlugin) Pages

func (BasePlugin) Pages() []PageDefinition

func (BasePlugin) RenderPage

func (BasePlugin) RenderPage(ctx *HookContext, pageType string) (string, gin.H)

func (BasePlugin) ScheduledJobs

func (BasePlugin) ScheduledJobs() []ScheduledJob

func (BasePlugin) Settings

func (BasePlugin) Settings() []SettingDefinition

func (BasePlugin) TemplateData

func (BasePlugin) TemplateData(ctx *HookContext) gin.H

func (BasePlugin) TemplateFooter

func (BasePlugin) TemplateFooter(ctx *HookContext) string

func (BasePlugin) TemplateHead

func (BasePlugin) TemplateHead(ctx *HookContext) string

type DynamicInfo

type DynamicInfo struct {
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	Version     string `json:"version"`
	Path        string `json:"path"`
	Runtime     string `json:"runtime"`
}

DynamicInfo describes a plugin loaded from a file at runtime.

type HookContext

type HookContext struct {
	GinContext *gin.Context
	DB         *gorm.DB
	Settings   map[string]string // plugin's own settings (namespace prefix stripped)
	Template   string            // which template is being rendered
	Data       gin.H             // the existing template data (read-only)

	// SubPath is set for RenderPage only: the request path after the page's
	// slug, without the leading slash. "" for /plugins, "hello" for
	// /plugins/hello, "index.json" for /plugins/index.json. Plugins that
	// don't use it can ignore it: blog only routes sub-paths to plugin pages.
	SubPath string
}

HookContext provides everything a plugin hook needs.

type Info

type Info struct {
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	Version     string `json:"version"`
	Runtime     string `json:"runtime,omitempty"`
}

Info is what `goblog validate-plugin` reports about a dynamic plugin file.

func Validate

func Validate(path string) (Info, error)

Validate loads a single dynamic plugin file through the Yaegi loader, exactly as LoadDynamicPlugins does at startup, and reports its identity. The plugin registry's CI runs it (via `goblog validate-plugin`) to check a submitted plugin loads and that its Name and Version match the manifest and release tag.

type PageDefinition

type PageDefinition struct {
	PageType    string // unique identifier, e.g. "research"
	Title       string // default title for nav and page heading
	Slug        string // default URL slug, e.g. "research"
	ShowInNav   bool   // whether to show in navigation by default
	NavOrder    int    // sort order in navigation
	Description string // help text for admin UI
}

PageDefinition describes a dynamic page type that a plugin provides. The plugin registers a page type and handles rendering when that page is visited. The page can optionally appear in the navigation.

type Plugin

type Plugin interface {
	Name() string
	DisplayName() string
	Version() string
	Settings() []SettingDefinition
	ScheduledJobs() []ScheduledJob
	TemplateData(ctx *HookContext) gin.H
	TemplateHead(ctx *HookContext) string
	TemplateFooter(ctx *HookContext) string
	OnInit(db *gorm.DB) error

	// Pages returns dynamic page types this plugin provides.
	Pages() []PageDefinition

	// RenderPage is called when a plugin-owned page is visited.
	// Returns the template name and data to render, or empty string to skip.
	RenderPage(ctx *HookContext, pageType string) (templateName string, data gin.H)
}

Plugin is the core interface. Embed BasePlugin to get no-op defaults and only implement the methods you need.

func LoadDynamicPlugin

func LoadDynamicPlugin(path string) (Plugin, error)

LoadDynamicPlugin loads one plugin source file through the interpreter.

func LoadDynamicPluginBytes

func LoadDynamicPluginBytes(src []byte) (Plugin, error)

LoadDynamicPluginBytes interprets plugin source and calls its NewPlugin(). The source runs as Go code inside this process; only load what you trust.

type PluginSetting

type PluginSetting struct {
	PluginName string `gorm:"primaryKey" json:"plugin_name"`
	Key        string `gorm:"primaryKey" json:"key"`
	Value      string `json:"value"`
}

PluginSetting stores a plugin's configuration in its own table, separate from the blog's core Setting table.

type PluginSettingsGroup

type PluginSettingsGroup struct {
	PluginName    string
	DisplayName   string
	Settings      []SettingDefinition
	CurrentValues map[string]string
}

PluginSettingsGroup holds a plugin's setting definitions and current values for rendering in the admin settings page.

type PluginStoreEntry

type PluginStoreEntry struct {
	PluginName string `gorm:"primaryKey;size:64"`
	Key        string `gorm:"primaryKey;size:256"`
	Value      []byte
	UpdatedAt  time.Time
}

PluginStoreEntry is one row of the plugin_store table.

func (PluginStoreEntry) TableName

func (PluginStoreEntry) TableName() string

type Post

type Post struct {
	ID        uint      `json:"id"`
	Title     string    `json:"title"`
	URL       string    `json:"url"`     // absolute under site_url; site-relative when site_url is unset
	Content   string    `json:"content"` // the post's Markdown source
	Tags      []string  `json:"tags"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Post is a published post as a plugin sees it through the posts_list host function. Its JSON field names are part of the wasm contract.

type Registry

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

Registry manages all registered plugins.

func NewRegistry

func NewRegistry(db *gorm.DB) *Registry

NewRegistry creates a plugin registry.

func (*Registry) DeletePages

func (r *Registry) DeletePages(pageTypes []string) error

DeletePages removes the blog.Page rows of the given page types — what ensurePages created for a plugin that is now being uninstalled. Types a still-registered plugin declares are skipped: that plugin's page is not the uninstalled one's to remove.

func (*Registry) DeleteSettings

func (r *Registry) DeleteSettings(name string)

DeleteSettings removes a plugin's stored settings (uninstall).

func (*Registry) Dynamic

func (r *Registry) Dynamic() []DynamicInfo

Dynamic lists the plugins that were loaded from files at runtime.

func (*Registry) GetAllSettings

func (r *Registry) GetAllSettings() []PluginSettingsGroup

GetAllSettings returns all plugin setting definitions grouped by plugin.

func (*Registry) GetNavItems

func (r *Registry) GetNavItems() []PageDefinition

GetNavItems returns navigation items from all enabled plugins that define pages.

func (*Registry) GetPagePlugin

func (r *Registry) GetPagePlugin(pageType string) Plugin

GetPagePlugin returns the plugin that owns a given page type, or nil.

func (*Registry) HasPageType

func (r *Registry) HasPageType(pageType string) bool

HasPageType returns true if any registered plugin (enabled or not) defines the given page type.

func (*Registry) Init

func (r *Registry) Init() error

Init seeds plugin settings and calls OnInit for every plugin. A plugin that fails does not stop the others; the failures are returned joined.

func (*Registry) InitPlugin

func (r *Registry) InitPlugin(name string) error

InitPlugin seeds settings, runs OnInit and starts the scheduled jobs of one plugin — what a hot install needs after RegisterDynamic.

func (*Registry) InjectTemplateData

func (r *Registry) InjectTemplateData(c *gin.Context, templateName string, data gin.H) gin.H

InjectTemplateData gathers data from all plugins and merges it into the template data map. Adds "plugins", "plugin_head_html", and "plugin_footer_html" keys. The plugin list is snapshotted and the lock released before any hook runs: a slow (or stuck-until-timeout) wasm plugin must not hold up registration, uninstall or every other request.

func (*Registry) IsPageTypeEnabled

func (r *Registry) IsPageTypeEnabled(pageType string) bool

IsPageTypeEnabled returns true if the plugin that owns the given page type is enabled.

func (*Registry) IsPluginEnabled

func (r *Registry) IsPluginEnabled(pluginName string) bool

IsPluginEnabled checks if a plugin is enabled via its settings.

func (*Registry) PluginSettings

func (r *Registry) PluginSettings(pluginName string) (PluginSettingsGroup, bool)

PluginSettings returns one plugin's setting definitions and current values, and whether a plugin by that name is registered. Unlike GetAllSettings it includes a plugin that declares no settings, since the enabled switch applies to every plugin.

func (*Registry) Plugins

func (r *Registry) Plugins() []Plugin

Plugins returns the list of registered plugins.

func (*Registry) Posts

func (r *Registry) Posts(limit int) ([]Post, error)

Posts returns the newest published posts, newest first: at most limit, clamped to 1..MaxPostsList. Drafts are never included.

func (*Registry) Register

func (r *Registry) Register(p Plugin)

Register adds a compiled-in plugin to the registry.

func (*Registry) RegisterDynamic

func (r *Registry) RegisterDynamic(p Plugin, path string) error

RegisterDynamic adds a plugin loaded from path at runtime. It fails when a plugin with the same Name() is already registered, since names key settings and pages.

func (*Registry) RenderPluginPage

func (r *Registry) RenderPluginPage(c *gin.Context, pageType, subPath string) (string, gin.H, bool)

RenderPluginPage renders a plugin-owned page. subPath is the request path after the page slug ("" for the page itself). Returns the template name, its data, and whether the request was handled. A plugin handles a request either by returning a template name or by writing the response itself (for example JSON), in which case the template name is empty and the caller must not render anything. The registry lock is not held while the plugin renders (GetPagePlugin releases it before returning).

func (*Registry) Search

func (r *Registry) Search(c *gin.Context, query string) []SearchResult

Search collects site-search results from every enabled plugin that implements Searcher, in registration order. As in InjectTemplateData, the plugin list is snapshotted and the lock released before any plugin runs.

func (*Registry) SitemapURLs

func (r *Registry) SitemapURLs(c *gin.Context) []SitemapURL

SitemapURLs collects sitemap entries from every enabled plugin that implements Sitemapper, in registration order, the lock released while plugins run.

func (*Registry) StartScheduledJobs

func (r *Registry) StartScheduledJobs()

StartScheduledJobs launches goroutines for all plugin scheduled jobs. Plugins whose jobs are already running are left alone.

func (*Registry) Stop

func (r *Registry) Stop()

Stop gracefully shuts down every plugin's scheduled jobs.

func (*Registry) Store

func (r *Registry) Store() Store

Store returns the registry's database-backed Store. It reads the current db on every call, so it keeps working after the wizard sets one.

func (*Registry) Unregister

func (r *Registry) Unregister(name string) error

Unregister removes a plugin and stops its scheduled jobs. Its settings are kept so a reinstall or update keeps the operator's configuration; use DeleteSettings to remove them. Yaegi cannot unload code, so a dynamic plugin's interpreter stays in memory until restart.

func (*Registry) UpdateDb

func (r *Registry) UpdateDb(db *gorm.DB)

UpdateDb updates the database reference (used after wizard setup).

func (*Registry) UpdateSetting

func (r *Registry) UpdateSetting(pluginName, key, value string)

UpdateSetting saves a single plugin setting.

type ScheduledJob

type ScheduledJob struct {
	Name     string
	Interval time.Duration
	Run      func(db *gorm.DB, settings map[string]string) error
}

ScheduledJob describes a periodic task the plugin wants to run.

type SearchResult

type SearchResult = blog.SearchHit

SearchResult is one hit a plugin contributes to the site search page: plain-text title, summary and kind label plus the URL to link to. It is blog's type so blog can render it without importing plugin.

type Searcher

type Searcher interface {
	Search(ctx *HookContext, query string) []SearchResult
}

Searcher is an optional interface: a plugin that implements it is asked for results when a visitor uses the site search, and they are listed after the matching posts. Only enabled plugins are asked.

type SettingDefinition

type SettingDefinition struct {
	Key          string // short key, e.g. "tracking_id"
	Type         string // "text" or "textarea"; anything else renders as a text input in the admin UI
	DefaultValue string
	Label        string // human-readable label for admin UI
	Description  string // help text
}

SettingDefinition describes a single setting that a plugin requires. Settings are stored in the plugin_settings table keyed by plugin name and setting key.

type SitemapURL

type SitemapURL = blog.SitemapURL

SitemapURL is one URL a plugin lists in /sitemap.xml: a site-relative path and, optionally, when it last changed. It is blog's type.

type Sitemapper

type Sitemapper interface {
	Sitemap(ctx *HookContext) []SitemapURL
}

Sitemapper is an optional interface: a plugin that implements it adds its pages' URLs to the site's sitemap — the pages under its slugs that blog cannot enumerate itself. Only enabled plugins are asked.

type Store

type Store interface {
	Get(pluginName, key string) (value []byte, found bool, err error)
	Set(pluginName, key string, value []byte) error
	Delete(pluginName, key string) error
	List(pluginName, prefix string) ([]string, error)
	DeleteAll(pluginName string) error
}

Store is the persistent key/value storage a plugin gets through the store_* host functions. Keys are namespaced by plugin name.

Directories

Path Synopsis
Package installer installs, updates and removes WebAssembly plugins from the plugin directory at runtime, for the admin UI.
Package installer installs, updates and removes WebAssembly plugins from the plugin directory at runtime, for the admin UI.
Package wasm runs WebAssembly plugins (Extism) behind the plugin.Plugin interface.
Package wasm runs WebAssembly plugins (Extism) behind the plugin.Plugin interface.

Jump to

Keyboard shortcuts

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