Documentation
¶
Overview ¶
Package runtime provides gin-kit's explicit application lifecycle and production-safe HTTP defaults on top of Gin.
Index ¶
- type Application
- func (a *Application) Cache() cache.Store
- func (a *Application) Close(ctx context.Context) error
- func (a *Application) Database() *runtimedb.Connection
- func (a *Application) DevTools() *devtools.DevTools
- func (a *Application) Go(name string, run func(context.Context) error)
- func (a *Application) Logger() *slog.Logger
- func (a *Application) Metrics() *metrics.Metrics
- func (a *Application) OnShutdown(hook func(context.Context) error)
- func (a *Application) OpenAPI() *openapi.Registry
- func (a *Application) OpenAPIDocument() *openapi.Document
- func (a *Application) Queue() *queue.Queue
- func (a *Application) Router() *gin.Engine
- func (a *Application) Run(ctx context.Context) error
- func (a *Application) String() string
- func (a *Application) Use(middleware ...gin.HandlerFunc)
- func (a *Application) Validator() *validation.Validator
- type CacheOptions
- type Check
- type DevToolsOptions
- type DocsOptions
- type HTTPOptions
- type MetricsOptions
- type Options
- type PProfOptions
- type QueueOptions
- type RateLimitOptions
- type RateLimiter
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
}
Application owns the Gin engine, managed infrastructure, and graceful lifecycle hooks created by New.
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() *runtimedb.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)
OnShutdown performs this package operation.
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
Router performs this package operation.
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
String performs this package operation.
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
Validator performs this package operation.
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
}
CacheOptions configures the cache store shared by application code.
type Check ¶
Check reports whether one required runtime dependency is ready to serve traffic. Readiness checks run with a short deadline and never affect liveness.
type DevToolsOptions ¶
type DevToolsOptions struct {
// Enabled serves the development dashboard. The runtime refuses to
// start when devtools are enabled outside the development environment.
Enabled bool
// Path is the dashboard mount point, defaulting to /_ginkit.
Path string
}
DevToolsOptions controls the development-only diagnostics dashboard.
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 is the optional human-readable OpenAPI description.
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 pairs with BasicAuthUsername to protect both docs routes.
BasicAuthPassword string
}
DocsOptions controls the generated OpenAPI document and Swagger UI routes.
type HTTPOptions ¶
type HTTPOptions struct {
// Address is the HTTP listen address, defaulting to :8080.
Address string
// ReadTimeout limits time spent reading an entire request.
ReadTimeout time.Duration
// WriteTimeout limits time spent writing one response.
WriteTimeout time.Duration
// IdleTimeout limits how long an idle keep-alive connection is retained.
IdleTimeout time.Duration
// ShutdownTimeout bounds graceful HTTP and runner shutdown.
ShutdownTimeout time.Duration
// MaxBodyBytes rejects larger request bodies with body_too_large.
MaxBodyBytes int64
// UI enables session- and template-oriented browser defaults.
UI bool
// CORSOrigins is the explicit allowlist for cross-origin browser requests.
CORSOrigins []string
// RateLimit configures the per-client request limiter.
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
}
HTTPOptions controls the server, request policy, and browser-facing behavior.
type MetricsOptions ¶
type MetricsOptions struct {
// Enabled mounts the metrics endpoint and records HTTP collectors.
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
}
MetricsOptions controls opt-in Prometheus HTTP instrumentation.
type Options ¶
type Options struct {
// Environment selects development or production safety behavior.
Environment string
// Logger receives runtime and request-scoped structured logs.
Logger *slog.Logger
// HTTP supplies server and middleware configuration.
HTTP HTTPOptions
// Validator replaces the default validator used by request binders.
Validator *validation.Validator
// ErrorMapper converts application errors into the canonical HTTP envelope.
ErrorMapper httpx.Mapper
// Readiness maps dependency names to checks exposed by the readiness route.
Readiness map[string]Check
// Database opens an owned database connection when non-nil.
Database *runtimedb.Config
// Metrics configures Prometheus instrumentation.
Metrics MetricsOptions
// PProf configures profiling routes.
PProf PProfOptions
// Cache configures the cache store returned by Application.Cache.
Cache CacheOptions
// Queue configures the queue returned by Application.Queue.
Queue QueueOptions
// Docs configures generated API documentation routes.
Docs DocsOptions
// DevTools configures the development-only diagnostics dashboard.
DevTools DevToolsOptions
}
Options assembles the runtime's explicit dependencies and safety policy.
type PProfOptions ¶
type PProfOptions struct {
// Enabled mounts profiling routes only when the application explicitly opts in.
Enabled bool
// Prefix is the mount point, defaulting to /debug/pprof. The endpoints
// expose process internals and must never be reachable publicly.
Prefix string
}
PProfOptions controls opt-in Go profiling routes.
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
}
QueueOptions configures the runtime-managed job queue.
type RateLimitOptions ¶
type RateLimitOptions struct {
// Enabled store data used by this type.
Enabled bool
// RequestsPerMinute store data used by this type.
RequestsPerMinute int
// Burst store data used by this type.
Burst int
// Key store data used by this type.
Key func(*gin.Context) string
}
RateLimitOptions defines an implementation type used by this package.
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
NewRateLimiter performs this package operation.
func (*RateLimiter) Middleware ¶
func (l *RateLimiter) Middleware() gin.HandlerFunc
Middleware performs this package operation.
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 runtime applications and converts it into runtime options.
|
Package config loads and validates environment configuration for gin-kit runtime applications and converts it into runtime 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 httpx provides gin-kit httpx implementation support.
|
Package httpx provides gin-kit httpx implementation support. |
|
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 oauth provides explicit OAuth 2.0 and OpenID Connect sign-in flows.
|
Package oauth provides explicit OAuth 2.0 and OpenID Connect sign-in flows. |
|
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. |
|
Package validation provides gin-kit validation implementation support.
|
Package validation provides gin-kit validation implementation support. |
|
Package whatsapp sends approved WhatsApp Business Platform templates through Meta's Cloud API.
|
Package whatsapp sends approved WhatsApp Business Platform templates through Meta's Cloud API. |