framework

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package framework provides gin-kit's explicit application lifecycle and production-safe HTTP defaults on top of Gin.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

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

func New

func New(options Options) (*Application, error)

func (*Application) Cache

func (a *Application) Cache() cache.Store

Cache returns the application cache store. It is never nil: without configuration an in-memory store is used, and CacheOptions selects Redis.

func (*Application) Close

func (a *Application) Close(ctx context.Context) error

Close releases application resources without serving: shutdown hooks run in reverse registration order, exactly once across Close and Run. Intended for tests and short-lived binaries that never call Run.

func (*Application) Database

func (a *Application) Database() *frameworkdb.Connection

Database returns the selected SQL/GORM/sqlx connection, when configured.

func (*Application) DevTools

func (a *Application) DevTools() *devtools.DevTools

DevTools returns the development dashboard, or nil when disabled. Guard uses accordingly, e.g. wrap the mailer into the devtools outbox only when the dashboard is on.

func (*Application) Go

func (a *Application) Go(name string, run func(context.Context) error)

Go registers a named background runner that Run supervises alongside the HTTP server: all runners share cancellation, and a runner error triggers a graceful application shutdown. Runners must return promptly once their context is canceled. Register runners before calling Run; later registrations are dropped with a warning.

func (*Application) Logger

func (a *Application) Logger() *slog.Logger

Logger returns the application's base structured logger. Handlers should prefer the request-scoped httpx.Logger(c).

func (*Application) Metrics

func (a *Application) Metrics() *metrics.Metrics

Metrics returns the Prometheus instrumentation, or nil when disabled. Use its Registry to register custom application metrics.

func (*Application) OnShutdown

func (a *Application) OnShutdown(hook func(context.Context) error)

func (*Application) OpenAPI

func (a *Application) OpenAPI() *openapi.Registry

OpenAPI returns the documentation registry. It is never nil, so generated code can describe operations unconditionally; the docs endpoints serve only when DocsOptions.Enabled is set.

func (*Application) OpenAPIDocument

func (a *Application) OpenAPIDocument() *openapi.Document

OpenAPIDocument builds the current OpenAPI document independent of docs endpoint configuration.

func (*Application) Queue

func (a *Application) Queue() *queue.Queue

Queue returns the application job queue. It is never nil: without configuration the sync driver executes jobs inline, and QueueOptions selects the supervised Redis worker.

func (*Application) Router

func (a *Application) Router() *gin.Engine

func (*Application) Run

func (a *Application) Run(ctx context.Context) error

Run serves until the context is canceled, the server fails, or a runner fails, then performs graceful shutdown: the HTTP server stops, runners are waited on, and hooks execute in reverse registration order.

func (*Application) String

func (a *Application) String() string

func (*Application) Use

func (a *Application) Use(middleware ...gin.HandlerFunc)

Use installs application middleware after gin-kit's safety middleware and before routes registered subsequently.

func (*Application) Validator

func (a *Application) Validator() *validation.Validator

type CacheOptions

type CacheOptions struct {
	// Driver selects the cache store: "memory" (default) or "redis".
	Driver string
	// Prefix is prepended to every cache key on shared stores.
	Prefix string
	// RedisURL configures the redis driver, e.g. redis://localhost:6379/0.
	RedisURL string
}

type Check

type Check func(context.Context) error

type DevToolsOptions

type DevToolsOptions struct {
	// Enabled serves the development dashboard. The framework refuses to
	// start when devtools are enabled outside the development environment.
	Enabled bool
	// Path is the dashboard mount point, defaulting to /_ginkit.
	Path string
}

type DocsOptions

type DocsOptions struct {
	// Enabled serves the OpenAPI spec and Swagger UI.
	Enabled bool
	// Path is the Swagger UI page, defaulting to /docs.
	Path string
	// SpecPath is the JSON document, defaulting to /openapi.json.
	SpecPath string
	// Title defaults to "API".
	Title string
	// Version defaults to "0.1.0".
	Version     string
	Description string
	// Servers lists the base URLs shown in the spec.
	Servers []string
	// BasicAuthUsername and BasicAuthPassword, when both set, protect the
	// docs and spec endpoints with HTTP basic auth.
	BasicAuthUsername string
	BasicAuthPassword string
}

type HTTPOptions

type HTTPOptions struct {
	Address         string
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	IdleTimeout     time.Duration
	ShutdownTimeout time.Duration
	MaxBodyBytes    int64
	UI              bool
	CORSOrigins     []string
	RateLimit       RateLimitOptions
	// TrustedProxies lists proxy IPs or CIDRs whose forwarded headers
	// (X-Forwarded-For) are honored when resolving client addresses. When
	// empty, no proxy is trusted and the socket peer address is used.
	TrustedProxies []string
}

type MetricsOptions

type MetricsOptions struct {
	Enabled bool
	// Path is the scrape endpoint, defaulting to /metrics.
	Path string
	// Registry optionally receives the HTTP collectors instead of a new
	// registry with the standard Go and process collectors.
	Registry *prometheus.Registry
}

type Options

type Options struct {
	Environment string
	Logger      *slog.Logger
	HTTP        HTTPOptions
	Validator   *validation.Validator
	ErrorMapper httpx.Mapper
	Readiness   map[string]Check
	Database    *frameworkdb.Config
	Metrics     MetricsOptions
	PProf       PProfOptions
	Cache       CacheOptions
	Queue       QueueOptions
	Docs        DocsOptions
	DevTools    DevToolsOptions
}

type PProfOptions

type PProfOptions struct {
	Enabled bool
	// Prefix is the mount point, defaulting to /debug/pprof. The endpoints
	// expose process internals and must never be reachable publicly.
	Prefix string
}

type QueueOptions

type QueueOptions struct {
	// Driver selects the job backend: "sync" (default, inline execution) or
	// "redis" (asynq worker supervised by Run).
	Driver string
	// RedisURL configures the redis driver, e.g. redis://localhost:6379/0.
	RedisURL string
	// Concurrency is the redis worker goroutine count, defaulting to 10.
	Concurrency int
}

type RateLimitOptions

type RateLimitOptions struct {
	Enabled           bool
	RequestsPerMinute int
	Burst             int
	Key               func(*gin.Context) string
}

type RateLimiter

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

RateLimiter is an in-memory limiter that can be installed selectively on routes or route groups when different policies are needed.

func NewRateLimiter

func NewRateLimiter(options RateLimitOptions) *RateLimiter

func (*RateLimiter) Middleware

func (l *RateLimiter) Middleware() gin.HandlerFunc

Directories

Path Synopsis
Package apptest provides small helpers for exercising a gin-kit application in tests and decoding its envelope responses.
Package apptest provides small helpers for exercising a gin-kit application in tests and decoding its envelope responses.
Package auth provides signed access and rotating refresh-token primitives.
Package auth provides signed access and rotating refresh-token primitives.
Package authz provides explicit, allowlist-style authorization decisions.
Package authz provides explicit, allowlist-style authorization decisions.
Package browsertest provides Playwright helpers for end-to-end browser tests against a gin-kit application.
Package browsertest provides Playwright helpers for end-to-end browser tests against a gin-kit application.
Package cache provides a small cache contract with in-memory and Redis drivers behind one small interface.
Package cache provides a small cache contract with in-memory and Redis drivers behind one small interface.
Package config loads and validates environment configuration for gin-kit framework applications and converts it into framework options.
Package config loads and validates environment configuration for gin-kit framework applications and converts it into framework options.
Package database provides explicit SQL, GORM, and sqlx connectors.
Package database provides explicit SQL, GORM, and sqlx connectors.
Package devtools serves gin-kit's development dashboard: a request log, mail outbox, route list, redacted config report, and queue statistics behind a single mount point.
Package devtools serves gin-kit's development dashboard: a request log, mail outbox, route list, redacted config report, and queue statistics behind a single mount point.
Package events provides a dependency-free, in-process, typed event bus.
Package events provides a dependency-free, in-process, typed event bus.
Package factory provides model factories for tests and seeders: define how a model is built once, then Make in-memory instances or Create persisted ones in tests and seeders.
Package factory provides model factories for tests and seeders: define how a model is built once, then Make in-memory instances or Create persisted ones in tests and seeders.
Package flags provides a small, in-memory set of boolean feature flags.
Package flags provides a small, in-memory set of boolean feature flags.
Package mail provides transactional email with a fluent message builder, an SMTP driver, and a development log driver.
Package mail provides transactional email with a fluent message builder, an SMTP driver, and a development log driver.
Package metrics provides opt-in Prometheus instrumentation for gin-kit applications.
Package metrics provides opt-in Prometheus instrumentation for gin-kit applications.
Package openapi builds OpenAPI 3.0.3 documents for gin-kit applications without annotations: every live route is documented from the router table, and operations described by generated code are enriched with typed schemas.
Package openapi builds OpenAPI 3.0.3 documents for gin-kit applications without annotations: every live route is documented from the router table, and operations described by generated code are enriched with typed schemas.
Package password provides Argon2id password hashing with encoded parameters.
Package password provides Argon2id password hashing with encoded parameters.
Package query provides allowlist-based filtering, sorting, and pagination for list endpoints, driven by bracketed query parameters.
Package query provides allowlist-based filtering, sorting, and pagination for list endpoints, driven by bracketed query parameters.
Package queue provides explicit background jobs with typed handler registration, an inline sync driver for development, and a Redis (asynq) driver for production with retries, delays, and graceful drain.
Package queue provides explicit background jobs with typed handler registration, an inline sync driver for development, and a Redis (asynq) driver for production with retries, delays, and graceful drain.
Package realtime provides explicit, in-process fan-out over WebSocket and server-sent events.
Package realtime provides explicit, in-process fan-out over WebSocket and server-sent events.
Package schedule provides cron-style task scheduling on robfig/cron with per-job panic recovery, optional overlap skipping, and graceful stop as an application runner.
Package schedule provides cron-style task scheduling on robfig/cron with per-job panic recovery, optional overlap skipping, and graceful stop as an application runner.
Package session provides encrypted cookie sessions, one-shot flash messages, and CSRF protection for UI-mode applications.
Package session provides encrypted cookie sessions, one-shot flash messages, and CSRF protection for UI-mode applications.
Package storage provides a file storage abstraction with a path-confined local driver and an S3-compatible driver.
Package storage provides a file storage abstraction with a path-confined local driver and an S3-compatible driver.

Jump to

Keyboard shortcuts

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