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
- Variables
- func LoadDynamicPlugins(registry *Registry, dir string)
- func Middleware(registry *Registry) gin.HandlerFunc
- func PageSlug(db *gorm.DB, pageType, def string) string
- type BasePlugin
- func (BasePlugin) OnInit(db *gorm.DB) error
- func (BasePlugin) Pages() []PageDefinition
- func (BasePlugin) RenderPage(ctx *HookContext, pageType string) (string, gin.H)
- func (BasePlugin) ScheduledJobs() []ScheduledJob
- func (BasePlugin) Settings() []SettingDefinition
- func (BasePlugin) TemplateData(ctx *HookContext) gin.H
- func (BasePlugin) TemplateFooter(ctx *HookContext) string
- func (BasePlugin) TemplateHead(ctx *HookContext) string
- type DynamicInfo
- type HookContext
- type Info
- type PageDefinition
- type Plugin
- type PluginSetting
- type PluginSettingsGroup
- type PluginStoreEntry
- type Post
- type Registry
- func (r *Registry) DeletePages(pageTypes []string) error
- func (r *Registry) DeleteSettings(name string)
- func (r *Registry) Dynamic() []DynamicInfo
- func (r *Registry) GetAllSettings() []PluginSettingsGroup
- func (r *Registry) GetNavItems() []PageDefinition
- func (r *Registry) GetPagePlugin(pageType string) Plugin
- func (r *Registry) HasPageType(pageType string) bool
- func (r *Registry) Init() error
- func (r *Registry) InitPlugin(name string) error
- func (r *Registry) InjectTemplateData(c *gin.Context, templateName string, data gin.H) gin.H
- func (r *Registry) IsPageTypeEnabled(pageType string) bool
- func (r *Registry) IsPluginEnabled(pluginName string) bool
- func (r *Registry) PluginSettings(pluginName string) (PluginSettingsGroup, bool)
- func (r *Registry) Plugins() []Plugin
- func (r *Registry) Posts(limit int) ([]Post, error)
- func (r *Registry) Register(p Plugin)
- func (r *Registry) RegisterDynamic(p Plugin, path string) error
- func (r *Registry) RenderPluginPage(c *gin.Context, pageType, subPath string) (string, gin.H, bool)
- func (r *Registry) Search(c *gin.Context, query string) []SearchResult
- func (r *Registry) SitemapURLs(c *gin.Context) []SitemapURL
- func (r *Registry) StartScheduledJobs()
- func (r *Registry) Stop()
- func (r *Registry) Store() Store
- func (r *Registry) Unregister(name string) error
- func (r *Registry) UpdateDb(db *gorm.DB)
- func (r *Registry) UpdateSetting(pluginName, key, value string)
- type ScheduledJob
- type SearchResult
- type Searcher
- type SettingDefinition
- type SitemapURL
- type Sitemapper
- type Store
Constants ¶
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 )
const MaxPostsList = 50
MaxPostsList caps how many posts one posts_list call returns.
Variables ¶
ErrStoreUnavailable is returned before the database is configured (wizard).
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 ¶
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.
Types ¶
type BasePlugin ¶
type BasePlugin struct{}
BasePlugin provides no-op implementations of all Plugin methods.
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 ¶
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"
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
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 ¶
LoadDynamicPlugin loads one plugin source file through the interpreter.
func LoadDynamicPluginBytes ¶
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 (*Registry) DeletePages ¶
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 ¶
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 ¶
GetPagePlugin returns the plugin that owns a given page type, or nil.
func (*Registry) HasPageType ¶
HasPageType returns true if any registered plugin (enabled or not) defines the given page type.
func (*Registry) Init ¶
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 ¶
InitPlugin seeds settings, runs OnInit and starts the scheduled jobs of one plugin — what a hot install needs after RegisterDynamic.
func (*Registry) InjectTemplateData ¶
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 ¶
IsPageTypeEnabled returns true if the plugin that owns the given page type is enabled.
func (*Registry) IsPluginEnabled ¶
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) Posts ¶
Posts returns the newest published posts, newest first: at most limit, clamped to 1..MaxPostsList. Drafts are never included.
func (*Registry) RegisterDynamic ¶
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 ¶
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 ¶
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 ¶
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) UpdateSetting ¶
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 ¶
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.
Source Files
¶
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. |