server

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package server exposes the drop-in GoMyAdmin HTTP server.

Existing Go applications can mount AdminServer.Handler on any router that accepts http.Handler. Use Config.DatabaseURL or Config.Pool for the built-in PostgreSQL adapter, or Config.Store for custom databases and ORMs.

Package server provides a drop-in HTTP handler for a GoMyAdmin admin panel.

Any existing Go HTTP server can mount an admin panel in three steps:

  1. Define your resources with admin.App.
  2. Create an AdminServer with New.
  3. Mount the handler returned by Handler().

Example:

app := admin.New("My App")
app.Resource(User{}).Label("Users").Field("ID").UUID().Primary().Readonly().
    Field("Email").Email().Required().Searchable()

srv, err := server.New(ctx, server.Config{
    DatabaseURL:  os.Getenv("DATABASE_URL"),
    App:          app,
    Authenticate: myAuthFunc,
})
if err != nil { log.Fatal(err) }
defer srv.Close()

mux.Handle("/admin/", srv.Handler())

Existing applications can pass Config.Store and Config.SessionStore to use their own database, ORM, service layer, Redis, Memcached, or cache system.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("record not found")

Functions

This section is empty.

Types

type ActionMeta added in v0.3.0

type ActionMeta = actionMeta

ActionMeta describes one resource action as exposed to clients and stores.

type AdminServer

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

AdminServer is a self-contained HTTP handler that serves a GoMyAdmin admin panel. Use New to create one, Handler to get the http.Handler, and Close when done.

func New

func New(ctx context.Context, cfg Config) (*AdminServer, error)

New creates an AdminServer.

With DatabaseURL or Pool, it uses the built-in PostgreSQL adapter and runs GoMyAdmin's internal migrations. With Config.Store, it uses the caller's adapter and does not require PostgreSQL.

func (*AdminServer) App

func (s *AdminServer) App() *admin.App

App returns the admin.App resource registry so callers can inspect or add resources after construction (before any requests are served).

func (*AdminServer) Close

func (s *AdminServer) Close()

Close releases the database pool when AdminServer created it (DatabaseURL was used). When you supplied your own Pool, close it yourself — AdminServer will not close it.

func (*AdminServer) Handler

func (s *AdminServer) Handler() http.Handler

Handler returns an http.Handler that serves all admin API routes under /admin/api/. Mount it at your mux root so the /admin/ prefix is routed here:

mux.Handle("/admin/", adminServer.Handler())

The handler is safe to call multiple times; it returns the same router each call.

type AdminStore added in v0.3.0

type AdminStore interface {
	HasResource(table string) bool
	Resources() []ResourceMeta
	List(ctx context.Context, table, tenantID, role, search, sortBy string, filters map[string]string, page, perPage int) ([]Record, int, error)
	Get(ctx context.Context, table, id, tenantID, role string) (Record, error)
	Create(ctx context.Context, table, tenantID string, input Record) (Record, error)
	Update(ctx context.Context, table, id, tenantID, role string, input Record) (oldRecord Record, newRecord Record, err error)
	Delete(ctx context.Context, table, id, tenantID, role string) (oldRecord Record, err error)
	DeleteMany(ctx context.Context, table string, ids []string, tenantID, role string) (oldRecords []Record, err error)
	RecordAudit(ctx context.Context, event AuditEvent)
	Audit(ctx context.Context, tenantID, role string) ([]AuditEvent, error)
	AddFile(ctx context.Context, record Record) error
	Files(ctx context.Context, tenantID, role string) ([]Record, error)
	FileKey(ctx context.Context, id, tenantID, role string) (string, error)
}

AdminStore is the database boundary for the drop-in admin server.

Implement this interface to mount GoMyAdmin on an existing Go backend without adopting the built-in PostgreSQL adapter. A Store can be backed by pgx, database/sql, GORM, sqlc, Ent, Bun, MongoDB, DynamoDB, SQLite, MySQL, or an internal service API.

type AuditEvent added in v0.3.0

type AuditEvent = auditEvent

AuditEvent describes one admin audit entry.

type Config

type Config struct {
	// DatabaseURL is a PostgreSQL connection string (e.g. "postgres://user:pass@host/db").
	// Mutually exclusive with Pool.
	DatabaseURL string

	// Pool is a pre-existing *pgxpool.Pool.
	// Mutually exclusive with DatabaseURL.
	// The caller remains responsible for closing it; AdminServer.Close() will not close it.
	Pool *pgxpool.Pool

	// Store is a custom persistence adapter.
	// Supply this when your application already uses another database, ORM, or
	// service layer. When Store is set, DatabaseURL and Pool are optional and no
	// PostgreSQL migrations are run by GoMyAdmin.
	Store AdminStore

	// SessionStore overrides the built-in PostgreSQL session store.
	// Use this for Redis, Memcached, database/sql, or an existing cache layer.
	// When omitted with DatabaseURL/Pool, PostgreSQL sessions are used. When
	// omitted with Store-only configuration, an in-memory session store is used.
	SessionStore auth.SessionStore

	// APIKeys enables API key authentication and management endpoints.
	// When omitted with DatabaseURL/Pool, a PostgreSQL-backed implementation is used.
	// When omitted with Store-only configuration, API key endpoints remain disabled.
	APIKeys auth.APIKeyManager

	// App is the resource registry built with admin.New and app.Resource().
	// An empty App is created automatically when nil.
	App *admin.App

	// Authenticate is called on every login attempt.
	// Return (actor, true, nil) on success or (zero, false, nil) on bad credentials.
	// When nil, all login attempts return 401 Unauthorized.
	Authenticate func(ctx context.Context, email, password string) (admin.Actor, bool, error)

	// OAuthProviders enables OAuth login flows keyed by provider name (for example "google").
	OAuthProviders map[string]auth.OAuthProvider

	// ResolveOAuthActor maps an OAuth identity to an admin.Actor.
	// Return (actor, true, nil) on success, (zero, false, nil) to deny login.
	ResolveOAuthActor func(ctx context.Context, provider string, identity auth.OAuthIdentity) (admin.Actor, bool, error)

	// Tenants is an optional callback that returns the list of tenants the actor
	// may switch to. The response appears in the "me" endpoint under "tenants".
	// When nil, an empty list is returned.
	Tenants func(ctx context.Context, actor admin.Actor) ([]map[string]string, error)

	// Log is the structured logger. Defaults to JSON on stderr.
	Log *slog.Logger

	// UploadDir is the local directory used by the built-in file upload handler.
	// Defaults to "tmp/uploads". Supply a storage.Storage via the Uploads field
	// instead to use S3, R2, or MinIO.
	UploadDir string

	// Uploads overrides the default local file storage adapter.
	// Set this to use S3, R2, or MinIO for file uploads.
	Uploads storage.Storage

	// PublicURL is the externally reachable base URL of this server.
	// Used as the Access-Control-Allow-Origin header value.
	// Defaults to GOMYADMIN_PUBLIC_URL env var, then "http://localhost:8080".
	PublicURL string

	// SigningSecret is used to sign OAuth state cookies.
	// Defaults to GOMYADMIN_SESSION_SECRET, then a development fallback.
	SigningSecret string

	// OAuthSuccessURL is where OAuth callbacks redirect after a successful login.
	// Defaults to "/admin/dashboard".
	OAuthSuccessURL string

	// OAuthFailureURL is where OAuth callbacks redirect after a failed login.
	// Defaults to "/admin/login".
	OAuthFailureURL string
	// contains filtered or unexported fields
}

Config holds all options for an AdminServer.

type FieldMeta added in v0.3.0

type FieldMeta = fieldMeta

FieldMeta describes one resource field as exposed to clients and stores.

type Record added in v0.3.0

type Record = map[string]any

Record is a generic database row or JSON payload used by AdminStore adapters.

type ResourceMeta added in v0.3.0

type ResourceMeta = resourceMeta

ResourceMeta describes one admin resource as exposed to clients and stores.

type ResourceMetadataStore added in v0.3.0

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

ResourceMetadataStore is a small helper store for adapters that want to reuse GoMyAdmin's resource metadata conversion while implementing persistence themselves.

func NewResourceMetadataStore added in v0.3.0

func NewResourceMetadataStore(app *admin.App) ResourceMetadataStore

NewResourceMetadataStore creates metadata from an admin.App. Custom stores can embed or compose this value to implement HasResource and Resources.

func (ResourceMetadataStore) HasResource added in v0.3.0

func (s ResourceMetadataStore) HasResource(table string) bool

func (ResourceMetadataStore) Resources added in v0.3.0

func (s ResourceMetadataStore) Resources() []ResourceMeta

Jump to

Keyboard shortcuts

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