dashboard

package
v0.9.12 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

README

Dashboard Extension v3.0.0

Extensible micro-frontend shell for building admin dashboards with Forge. Contributors (local or remote) register pages, widgets, and settings that are merged into a unified dashboard powered by ForgeUI.

Features

  • ForgeUI Integration -- layouts, routing, theming, and HTMX-powered partial navigation
  • Contributor System -- local (in-process gomponents) and remote (HTTP fragment proxy) contributors
  • Go-JS Bridge -- call Go functions from the browser via Alpine.js $go() magic helpers
  • SSE Real-Time -- server-sent events for live metric and health updates
  • Federated Search -- cross-contributor search with the SearchableContributor interface
  • Settings Aggregation -- contributor settings merged into a unified settings page
  • Data Export -- JSON, CSV, and Prometheus export formats
  • Service Discovery -- auto-discover remote contributors via the discovery extension
  • Security -- Content-Security-Policy headers, CSRF tokens, HTML sanitization
  • Theming -- auto, light, and dark modes with custom CSS injection

Quick Start

go get github.com/xraph/forge/extensions/dashboard
package main

import (
    "log"
    "time"

    "github.com/xraph/forge"
    "github.com/xraph/forge/extensions/dashboard"
)

func main() {
    app := forge.New(
        forge.WithAppName("my-app"),
        forge.WithAppVersion("1.0.0"),
    )

    if err := app.RegisterExtension(dashboard.NewExtension(
        dashboard.WithTitle("My Dashboard"),
        dashboard.WithBasePath("/dashboard"),
        dashboard.WithRealtime(true),
        dashboard.WithRefreshInterval(30 * time.Second),
        dashboard.WithExport(true),
    )); err != nil {
        log.Fatalf("failed to register dashboard: %v", err)
    }

    if err := app.Run(); err != nil {
        log.Fatalf("application error: %v", err)
    }
}

The dashboard is available at http://localhost:8080/dashboard.

Architecture

ForgeUI App
  |-- Layouts (root -> dashboard/base/full/settings)
  |-- Pages (overview, health, metrics, services)
  |-- Contributors
  |     |-- Local (in-process, gomponents)
  |     +-- Remote (HTTP fragment proxy)
  |-- Bridge (Go <-> JS function calls)
  |-- SSE Broker (real-time events)
  +-- Search / Settings / Export

The dashboard uses ForgeUI's layout and routing system. The root layout renders the HTML shell with HTMX, Alpine.js, and the sidebar. On HTMX partial requests (HX-Request header), only the page content is returned without the outer HTML shell.

Contributors provide pages, widgets, and settings via a manifest-driven system. Local contributors render gomponents nodes directly. Remote contributors serve HTML fragments over HTTP, which the dashboard proxies and embeds.

Configuration

All options use the functional options pattern:

Option Default Description
WithBasePath(path) "/dashboard" HTTP base path
WithTitle(title) "Forge Dashboard" Page title
WithRealtime(bool) true SSE real-time updates
WithExport(bool) true Data export endpoints
WithSearch(bool) true Federated search
WithSettings(bool) true Settings aggregation
WithDiscovery(bool) false Auto-discover remote contributors
WithBridge(bool) true Go-JS bridge functions
WithRefreshInterval(d) 30s Data collection interval
WithHistoryDuration(d) 1h Data retention window
WithMaxDataPoints(n) 1000 Max retained data points
WithTheme(theme) "auto" Theme: auto, light, dark
WithCSP(bool) true Content-Security-Policy
WithCSRF(bool) true CSRF token protection

See full configuration reference for all 22 options.

Contributor System

Extensions contribute UI to the dashboard by implementing the LocalContributor interface:

type UsersContributor struct{}

func (c *UsersContributor) Manifest() *contributor.Manifest {
    return &contributor.Manifest{
        Name:        "users",
        DisplayName: "User Management",
        Icon:        "users",
        Nav: []contributor.NavItem{
            {Label: "Users", Path: "/", Icon: "users", Group: "Identity"},
            {Label: "Roles", Path: "/roles", Icon: "shield", Group: "Identity"},
        },
        Widgets: []contributor.WidgetDescriptor{
            {ID: "active-users", Title: "Active Users", Size: "sm", RefreshSec: 60},
        },
    }
}

func (c *UsersContributor) RenderPage(ctx context.Context, route string, params contributor.Params) (g.Node, error) {
    // Return gomponents nodes
}

func (c *UsersContributor) RenderWidget(ctx context.Context, widgetID string) (g.Node, error) {
    // Return widget content
}

func (c *UsersContributor) RenderSettings(ctx context.Context, settingID string) (g.Node, error) {
    // Return settings panel
}

Register with the dashboard:

dashExt := dashExt.(*dashboard.Extension)
dashExt.RegisterContributor(&UsersContributor{})

Remote contributors are separate HTTP services that expose fragment endpoints. They can be registered manually or auto-discovered via the discovery extension.

Bridge Functions

The Go-JS bridge lets the dashboard UI call Go functions from Alpine.js:

// Register a custom bridge function
dashExt.RegisterBridgeFunction("myapp.getData", func(ctx bridge.Context, params MyParams) (*MyResult, error) {
    // Go logic here
    return result, nil
}, bridge.WithDescription("Get application data"))

From the browser:

// Alpine.js
const data = await $go('myapp.getData', { key: 'value' })

8 built-in functions are registered automatically: dashboard.getOverview, dashboard.getHealth, dashboard.getMetrics, dashboard.getServices, dashboard.getServiceDetail, dashboard.getHistory, dashboard.getMetricsReport, dashboard.refresh.

HTTP Endpoints

All routes are under the configured base path (default /dashboard):

Category Path Description
Pages / Dashboard overview
Pages /health Health status page
Pages /metrics Metrics page
Pages /services Services page
API /api/overview Overview JSON
API /api/health Health JSON
API /api/metrics Metrics JSON
API /api/services Services JSON
API /api/service-detail?name=X Service detail JSON
API /api/history History JSON
API /api/metrics-report Metrics report JSON
Export /export/json Full JSON export
Export /export/csv CSV export
Export /export/prometheus Prometheus format
Real-time /sse SSE event stream
Bridge /bridge/call Bridge function call (POST)
Bridge /bridge/stream/ Bridge streaming (SSE)
Search /api/search?q=X Federated search
Contributor /ext/:name/pages/* Local contributor pages
Contributor /ext/:name/widgets/:id Local contributor widgets
Remote /remote/:name/pages/* Remote contributor pages
Remote /remote/:name/widgets/:id Remote contributor widgets
Settings /settings Settings index
Settings /ext/:name/settings/:id Contributor settings

Examples

  • basic -- Minimal dashboard with built-in pages only
  • contributor -- Custom local contributor with pages, widgets, and settings
  • remote -- Remote contributor registration and service discovery

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPageNotFound is returned when a requested page does not exist.
	ErrPageNotFound = errors.New("dashboard: page not found")

	// ErrWidgetNotFound is returned when a requested widget does not exist.
	ErrWidgetNotFound = errors.New("dashboard: widget not found")

	// ErrSettingNotFound is returned when a requested setting does not exist.
	ErrSettingNotFound = errors.New("dashboard: setting not found")

	// ErrContributorExists is returned when a contributor with the same name is already registered.
	ErrContributorExists = errors.New("dashboard: contributor already registered")

	// ErrContributorNotFound is returned when a contributor is not found in the registry.
	ErrContributorNotFound = errors.New("dashboard: contributor not found")

	// ErrRemoteUnreachable is returned when a remote contributor cannot be reached.
	ErrRemoteUnreachable = errors.New("dashboard: remote contributor unreachable")

	// ErrManifestFetch is returned when fetching a remote manifest fails.
	ErrManifestFetch = errors.New("dashboard: failed to fetch remote manifest")

	// ErrDiscoveryTimeout is returned when service discovery times out.
	ErrDiscoveryTimeout = errors.New("dashboard: service discovery timed out")

	// ErrRecoveryFailed is returned when UI recovery fails.
	ErrRecoveryFailed = errors.New("dashboard: UI recovery failed")

	// ErrCollectorNotInitialized is returned when the data collector is not initialized.
	ErrCollectorNotInitialized = errors.New("dashboard: collector not initialized")
)

Functions

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new dashboard extension.

Types

type Config

type Config struct {
	// Server settings
	BasePath string `json:"base_path" yaml:"base_path"`
	Title    string `json:"title"     yaml:"title"`

	// Features
	EnableRealtime  bool `json:"enable_realtime"  yaml:"enable_realtime"` // SSE real-time updates
	EnableExport    bool `json:"enable_export"    yaml:"enable_export"`
	EnableSearch    bool `json:"enable_search"    yaml:"enable_search"`
	EnableSettings  bool `json:"enable_settings"  yaml:"enable_settings"`
	EnableDiscovery bool `json:"enable_discovery" yaml:"enable_discovery"` // auto-discover remote contributors
	EnableBridge    bool `json:"enable_bridge"    yaml:"enable_bridge"`    // Go↔JS bridge function system

	// Data collection
	RefreshInterval time.Duration `json:"refresh_interval" yaml:"refresh_interval"`
	HistoryDuration time.Duration `json:"history_duration" yaml:"history_duration"`
	MaxDataPoints   int           `json:"max_data_points"  yaml:"max_data_points"`

	// Proxy/Remote
	ProxyTimeout time.Duration `json:"proxy_timeout" yaml:"proxy_timeout"`
	CacheMaxSize int           `json:"cache_max_size" yaml:"cache_max_size"`
	CacheTTL     time.Duration `json:"cache_ttl"      yaml:"cache_ttl"`

	// SSE
	SSEKeepAlive time.Duration `json:"sse_keep_alive" yaml:"sse_keep_alive"`

	// Security
	EnableCSP  bool `json:"enable_csp"  yaml:"enable_csp"`
	EnableCSRF bool `json:"enable_csrf" yaml:"enable_csrf"`

	// Theming
	Theme     string `json:"theme"      yaml:"theme"` // light, dark, auto
	CustomCSS string `json:"custom_css" yaml:"custom_css"`

	// Discovery
	DiscoveryTag          string        `json:"discovery_tag"           yaml:"discovery_tag"`
	DiscoveryPollInterval time.Duration `json:"discovery_poll_interval" yaml:"discovery_poll_interval"`

	// Export
	ExportFormats []string `json:"export_formats" yaml:"export_formats"`

	// Internal
	RequireConfig bool `json:"-" yaml:"-"`
}

Config contains dashboard extension configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default dashboard configuration.

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for Config.

func WithBasePath

func WithBasePath(path string) ConfigOption

WithBasePath sets the base URL path for the dashboard.

func WithBridge added in v0.9.12

func WithBridge(enabled bool) ConfigOption

WithBridge enables or disables the Go↔JS bridge function system.

func WithCSP added in v0.9.12

func WithCSP(enabled bool) ConfigOption

WithCSP enables or disables Content-Security-Policy headers.

func WithCSRF added in v0.9.12

func WithCSRF(enabled bool) ConfigOption

WithCSRF enables or disables CSRF token protection.

func WithCacheMaxSize added in v0.9.12

func WithCacheMaxSize(size int) ConfigOption

WithCacheMaxSize sets the maximum number of cached fragments.

func WithCacheTTL added in v0.9.12

func WithCacheTTL(ttl time.Duration) ConfigOption

WithCacheTTL sets the time-to-live for cached fragments.

func WithConfig

func WithConfig(config Config) ConfigOption

WithConfig sets the complete config.

func WithCustomCSS added in v0.9.12

func WithCustomCSS(css string) ConfigOption

WithCustomCSS sets custom CSS to inject into the dashboard.

func WithDiscovery added in v0.9.12

func WithDiscovery(enabled bool) ConfigOption

WithDiscovery enables or disables automatic service discovery of remote contributors.

func WithDiscoveryPollInterval added in v0.9.12

func WithDiscoveryPollInterval(interval time.Duration) ConfigOption

WithDiscoveryPollInterval sets how often to poll for new contributors via discovery.

func WithDiscoveryTag added in v0.9.12

func WithDiscoveryTag(tag string) ConfigOption

WithDiscoveryTag sets the service discovery tag to filter dashboard contributors.

func WithExport

func WithExport(enabled bool) ConfigOption

WithExport enables or disables export functionality.

func WithExportFormats added in v0.9.12

func WithExportFormats(formats []string) ConfigOption

WithExportFormats sets the supported export formats.

func WithHistoryDuration

func WithHistoryDuration(duration time.Duration) ConfigOption

WithHistoryDuration sets the data retention duration.

func WithMaxDataPoints

func WithMaxDataPoints(maxPoints int) ConfigOption

WithMaxDataPoints sets the maximum number of data points to retain.

func WithProxyTimeout added in v0.9.12

func WithProxyTimeout(timeout time.Duration) ConfigOption

WithProxyTimeout sets the timeout for proxying requests to remote contributors.

func WithRealtime

func WithRealtime(enabled bool) ConfigOption

WithRealtime enables or disables real-time SSE updates.

func WithRefreshInterval

func WithRefreshInterval(interval time.Duration) ConfigOption

WithRefreshInterval sets the data collection refresh interval.

func WithRequireConfig

func WithRequireConfig(required bool) ConfigOption

WithRequireConfig requires config from ConfigManager.

func WithSSEKeepAlive added in v0.9.12

func WithSSEKeepAlive(interval time.Duration) ConfigOption

WithSSEKeepAlive sets the SSE keep-alive interval.

func WithSearch added in v0.9.12

func WithSearch(enabled bool) ConfigOption

WithSearch enables or disables global search.

func WithSettings added in v0.9.12

func WithSettings(enabled bool) ConfigOption

WithSettings enables or disables aggregated settings pages.

func WithTheme

func WithTheme(theme string) ConfigOption

WithTheme sets the UI theme (light, dark, auto).

func WithTitle

func WithTitle(title string) ConfigOption

WithTitle sets the dashboard title.

type CoreContributor added in v0.9.12

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

CoreContributor is the built-in contributor providing Overview, Health, Metrics, and Services pages. It implements contributor.LocalContributor.

func NewCoreContributor added in v0.9.12

func NewCoreContributor(c *collector.DataCollector, h *collector.DataHistory) *CoreContributor

NewCoreContributor creates a new CoreContributor.

func (*CoreContributor) Manifest added in v0.9.12

func (c *CoreContributor) Manifest() *contributor.Manifest

Manifest returns the core contributor's manifest.

func (*CoreContributor) RenderPage added in v0.9.12

func (c *CoreContributor) RenderPage(ctx context.Context, route string, params contributor.Params) (g.Node, error)

RenderPage renders a page for the given route.

func (*CoreContributor) RenderSettings added in v0.9.12

func (c *CoreContributor) RenderSettings(_ context.Context, _ string) (g.Node, error)

RenderSettings renders a settings panel. Core has no settings.

func (*CoreContributor) RenderWidget added in v0.9.12

func (c *CoreContributor) RenderWidget(ctx context.Context, widgetID string) (g.Node, error)

RenderWidget renders a specific widget by ID.

type DashboardBridge added in v0.9.12

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

DashboardBridge wraps a forgeui bridge.Bridge to provide Go↔JS communication for the dashboard. Bridge functions can be called from the browser via Alpine.js magic helpers ($go, $goBatch, $goStream) or the ForgeBridge JS client.

func NewDashboardBridge added in v0.9.12

func NewDashboardBridge(c *collector.DataCollector, h *collector.DataHistory) *DashboardBridge

NewDashboardBridge creates a new bridge with built-in dashboard functions registered.

func NewDashboardBridgeWithBridge added in v0.9.12

func NewDashboardBridgeWithBridge(b *bridge.Bridge, c *collector.DataCollector, h *collector.DataHistory) *DashboardBridge

NewDashboardBridgeWithBridge wraps an existing forgeui bridge instance with dashboard functions. Use this when the bridge is created by forgeui.App (via forgeui.WithBridge()).

func (*DashboardBridge) Bridge added in v0.9.12

func (db *DashboardBridge) Bridge() *bridge.Bridge

Bridge returns the underlying forgeui bridge instance.

func (*DashboardBridge) Register added in v0.9.12

func (db *DashboardBridge) Register(name string, handler any, opts ...bridge.FunctionOption) error

Register registers a custom bridge function. Extensions can use this to expose Go functions callable from the dashboard UI.

type EmptyParams added in v0.9.12

type EmptyParams struct{}

EmptyParams is used for functions that take no input.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements the extensible dashboard micro-frontend shell. Contributors (local or remote) register pages, widgets, and settings that are merged into a unified admin dashboard.

func (*Extension) CSRFManager added in v0.9.12

func (e *Extension) CSRFManager() *security.CSRFManager

CSRFManager returns the CSRF token manager. Returns nil if CSRF is disabled.

func (*Extension) Collector added in v0.8.0

func (e *Extension) Collector() *collector.DataCollector

Collector returns the data collector instance.

func (*Extension) DashboardBridge added in v0.9.12

func (e *Extension) DashboardBridge() *DashboardBridge

DashboardBridge returns the dashboard bridge instance for registering custom functions. Returns nil if the bridge is not enabled.

func (*Extension) Dependencies

func (e *Extension) Dependencies() []string

Dependencies returns extension dependencies.

func (*Extension) ForgeUIApp added in v0.9.12

func (e *Extension) ForgeUIApp() *forgeui.App

ForgeUIApp returns the forgeui application instance.

func (*Extension) FragmentProxy added in v0.9.12

func (e *Extension) FragmentProxy() *proxy.FragmentProxy

FragmentProxy returns the fragment proxy for remote contributors.

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks if the dashboard is healthy.

func (*Extension) History added in v0.8.0

func (e *Extension) History() *collector.DataHistory

History returns the data history instance.

func (*Extension) RecoveryManager added in v0.9.12

func (e *Extension) RecoveryManager() *recovery.Manager

RecoveryManager returns the recovery manager for remote contributors.

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the dashboard extension.

func (*Extension) RegisterBridgeFunction added in v0.9.12

func (e *Extension) RegisterBridgeFunction(name string, handler any, opts ...bridge.FunctionOption) error

RegisterBridgeFunction registers a custom bridge function callable from the dashboard UI. This is a convenience method — callers can also use DashboardBridge().Register() directly. Returns an error if the bridge is not enabled.

func (*Extension) RegisterContributor added in v0.9.12

func (e *Extension) RegisterContributor(c contributor.LocalContributor) error

RegisterContributor registers a local contributor with the dashboard. This is the primary API for extensions to contribute UI to the dashboard.

func (*Extension) Registry added in v0.9.12

func (e *Extension) Registry() *contributor.ContributorRegistry

Registry returns the contributor registry.

func (*Extension) SSEBroker added in v0.9.12

func (e *Extension) SSEBroker() *sse.Broker

SSEBroker returns the SSE event broker. Returns nil if real-time is disabled.

func (*Extension) Sanitizer added in v0.9.12

func (e *Extension) Sanitizer() *security.Sanitizer

Sanitizer returns the HTML sanitizer for remote fragments.

func (*Extension) Searcher added in v0.9.12

func (e *Extension) Searcher() *search.FederatedSearch

Searcher returns the federated search engine. Returns nil if search is disabled.

func (*Extension) SetDiscoveryService added in v0.9.12

func (e *Extension) SetDiscoveryService(svc dashboarddiscovery.DiscoveryService)

SetDiscoveryService configures the discovery service used to auto-discover remote dashboard contributors. Call this before Start() if discovery is enabled.

The discovery service must implement dashboarddiscovery.DiscoveryService (ListServices + DiscoverWithTags). The forge extensions/discovery.Service type satisfies this interface.

Example:

dashExt.SetDiscoveryService(discoveryExtension.Service())

func (*Extension) SettingsAggregator added in v0.9.12

func (e *Extension) SettingsAggregator() *settings.Aggregator

SettingsAggregator returns the settings aggregator. Returns nil if settings is disabled.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the dashboard extension.

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop stops the dashboard extension.

func (*Extension) ThemeManager added in v0.9.12

func (e *Extension) ThemeManager() *dashtheme.Manager

ThemeManager returns the theme manager.

type ServiceNameParams added in v0.9.12

type ServiceNameParams struct {
	Name string `json:"name"`
}

ServiceNameParams is used for functions that take a service name.

Directories

Path Synopsis
examples
basic command
Package main demonstrates a basic dashboard setup with built-in pages only.
Package main demonstrates a basic dashboard setup with built-in pages only.
contributor command
Package main demonstrates how to create a custom LocalContributor that adds pages, widgets, and settings to the dashboard.
Package main demonstrates how to create a custom LocalContributor that adds pages, widgets, and settings to the dashboard.
remote command
Package main demonstrates how to register a remote contributor with the dashboard extension.
Package main demonstrates how to register a remote contributor with the dashboard extension.
Package theme provides a dashboard-specific wrapper around the forgeui theme system.
Package theme provides a dashboard-specific wrapper around the forgeui theme system.
ui

Jump to

Keyboard shortcuts

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