Documentation
¶
Index ¶
- Constants
- Variables
- func BuildDirectTarget(endpoints []string) string
- func BuildEtcdTarget(endpoints []string, key string) string
- func BuildOpenAPI(cfg *ServiceConfig, models map[string]*db.TableInfo) (*openapi3.T, error)
- func BulkheadGet(name string) *syncx.Limit
- func BulkheadRegister(name string, limit int)
- func CachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, ...)
- func CheckScalarWarnings(cfg *ServiceConfig)
- func CheckVercelWarnings(cfg *ServiceConfig)
- func GenerateProto(info *db.TableInfo, modelName, svcName, pkg string) string
- func GenerateShortCode(n int) string
- func GetTable[T any](s *Service, name string) *db.Table[T]
- func GrpcCall[T any](ctx context.Context, gc *GrpcClient, ...) (T, error)
- func InsertOutbox(ctx context.Context, pool *pgxpool.Pool, subject string, payload []byte) error
- func InsertOutboxJSON(ctx context.Context, pool *pgxpool.Pool, subject string, data any) error
- func IsSameOrigin(referer string, requestHost string) bool
- func MongoMustRegister(svc *Service, name, poolName, database, collection, lookupField string)
- func MustGetGrpcServer(svc *Service) *grpc.Server
- func MustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func MySQLCachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, ...)
- func MySQLMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func Pool(pools map[string]any, name string) any
- func PoolPG(pools map[string]any, name string) *pgxpool.Pool
- func PoolPGRead(pools map[string]any, name string) *pgxpool.Pool
- func PoolSQL(pools map[string]any, name string) *sql.DB
- func PresignTTL(store any) time.Duration
- func RegisterEntries(app *fiber.App, cfg *ServiceConfig, handlers *EntryHandlers, prefix string, ...) error
- func SLOEvent(name string, isError bool)
- func SanitizeFilename(name string) string
- func SetRateLimitMaxFunc(fn func(c fiber.Ctx) int)
- func TableFor[T any](pools map[string]any, poolName, tableName string) (*db.Table[T], error)
- func TursoMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func ValidateProjectStructure(yamlPath string, target string) error
- func VerifyCallbackSignature(payload []byte, secret string, signature string) bool
- func WrapTransformHandler[T any](handler func(fiber.Ctx) error, hooks EntryHooks[T]) func(fiber.Ctx) error
- type APIKeyPrefillDef
- type AsyncCallbackConf
- type AsyncHandler
- type AsyncJobManager
- type AsyncReassignConf
- type AsyncStoreConf
- type AuthConfig
- type AuthCookieConfig
- type AuthPrefillDef
- type AutocertTLS
- type CORSConf
- type CORSGroupConf
- type CRUDFactory
- type CRUDOverrides
- type CRUDProvider
- func NewCRUDProvider[T any](table *db.Table[T], hooks EntryHooks[T]) CRUDProvider
- func NewMongoCRUDProvider(model *mon.Model, lookupField string) CRUDProvider
- func NewMySQLCRUDProvider[T any](table *db.MySQLTable[T], hooks EntryHooks[T]) CRUDProvider
- func NewTursoCRUDProvider[T any](table *db.TursoTable[T], hooks EntryHooks[T]) CRUDProvider
- type CSPConf
- type CSPGroupConf
- type CSRFConf
- type CacheConfig
- type ClientConnInterface
- type ContentSecurityDef
- type Cookie
- type CookieConf
- type CorrelationConf
- type CronJob
- type CronJobFunc
- type CronPublish
- type CronScheduler
- type CryptionDef
- type DBConfig
- type DefaultExitHooks
- type DefaultHooks
- func (DefaultHooks[T]) AfterCreate(_ context.Context, _ *T) error
- func (DefaultHooks[T]) AfterDelete(_ context.Context, _ string) error
- func (DefaultHooks[T]) AfterTransform(_ context.Context, _ any) error
- func (DefaultHooks[T]) AfterUpdate(_ context.Context, _ *T) error
- func (DefaultHooks[T]) BeforeCreate(_ context.Context, req T) (T, error)
- func (DefaultHooks[T]) BeforeDelete(_ context.Context, _ string) error
- func (DefaultHooks[T]) BeforeTransform(_ context.Context, req T) (T, error)
- func (DefaultHooks[T]) BeforeUpdate(_ context.Context, _ string, patch map[string]any) (map[string]any, error)
- type DeployConfig
- type DocsHooks
- type EncryptCookieDef
- type EntryDef
- type EntryHandlers
- type EntryHooks
- type EventPublishTarget
- type EventStreamConnConf
- type ExitHandler
- type ExitHooks
- type ExitWorker
- type ExitWorkerManager
- type FlashMessage
- type GCConfig
- type GrpcClient
- type GrpcClientConf
- type GrpcInterceptorsConfig
- type GrpcRegisterFn
- type GrpcServer
- type GrpcServerConf
- type HTTPClientDef
- type JobState
- type JobStatus
- type JobStore
- type KVConfig
- type KeysetResponse
- type ListParams
- type ManualTLS
- type Map
- type OldInputData
- type OpenAPIConf
- type OutboxRecord
- type OutboxRelay
- type PGPool
- type PaginatedResponse
- type PoolConf
- type PoolConfig
- type PoolHealth
- type PrometheusConfig
- type RateLimitConf
- type RateLimitDef
- type Reaper
- type Redirect
- func (r *Redirect) Back(fallback ...string) error
- func (r *Redirect) Message(key string) FlashMessage
- func (r *Redirect) Messages() []FlashMessage
- func (r *Redirect) OldInput(key string) OldInputData
- func (r *Redirect) OldInputs() []OldInputData
- func (r *Redirect) Route(name string, config ...RedirectConfig) error
- func (r *Redirect) Status(code int) *Redirect
- func (r *Redirect) To(location string) error
- func (r *Redirect) With(key, value string) *Redirect
- func (r *Redirect) WithInput() *Redirect
- type RedirectConfig
- type RedirectDef
- type RedisConfig
- type RefreshConfig
- type RestCtx
- func (c *RestCtx) Bind(v any) error
- func (c *RestCtx) Body() []byte
- func (c *RestCtx) Context() context.Context
- func (c *RestCtx) Get(key string) string
- func (c *RestCtx) JSON(data any) error
- func (c *RestCtx) Locals(key any, values ...any) any
- func (c *RestCtx) Method() string
- func (c *RestCtx) Params(key string) string
- func (c *RestCtx) Path() string
- func (c *RestCtx) PoolPG(name string) *pgxpool.Pool
- func (c *RestCtx) PoolRead(name string) *pgxpool.Pool
- func (c *RestCtx) PoolSQL(name string) *sql.DB
- func (c *RestCtx) Query(key string, defaultValue ...string) string
- func (c *RestCtx) Redirect() *Redirect
- func (c *RestCtx) ResponseBody() string
- func (c *RestCtx) SendStatus(code int) error
- func (c *RestCtx) SendString(s string) error
- func (c *RestCtx) Set(key, val string)
- func (c *RestCtx) SetCookie(cookie *Cookie)
- func (c *RestCtx) Status(code int) *RestCtx
- func (c *RestCtx) StatusCode() int
- func (c *RestCtx) Stream() io.Reader
- type RetryConf
- type RouteMW
- type SLOConfig
- type SSEHandler
- type SSRFConf
- type SecurityDef
- type SecurityHeadersConf
- type SeedFunc
- type ServerConf
- type ServerOverrideDef
- type Service
- func (s *Service) AddStatic(prefix, dir string, opts ...StaticOption) *Service
- func (s *Service) App() *fiber.App
- func (s *Service) GetGRPCClient(name string) *GrpcClient
- func (s *Service) GetGrpcServer() *GrpcServer
- func (s *Service) KV(name string) *redis.Redis
- func (s *Service) NATS(name string) events.EventBroker
- func (s *Service) Pool(name string) any
- func (s *Service) PoolPG(name string) any
- func (s *Service) PoolPGTyped(name string) *pgxpool.Pool
- func (s *Service) PoolRead(name string) *pgxpool.Pool
- func (s *Service) RegisterGrpcService(name string, fn func(srv *grpc.Server)) *Service
- func (s *Service) RegisterModel(name string, model any) *Service
- func (s *Service) RegisterValidation(name string, model any) *Service
- func (s *Service) Run() error
- func (s *Service) RunWithContext(ctx context.Context) error
- func (s *Service) SafeHTTPClient() *middleware.SafeHTTPClient
- func (s *Service) SetCORSOriginsFunc(name string, fn func(origin string) bool) *Service
- func (s *Service) Storage(path string) server.StorageBackend
- func (s *Service) Stream(name string) events.EventBroker
- func (s *Service) Table(name string) any
- func (s *Service) WithAPIKeyValidator(fn func(ctx context.Context, key string) (*middleware.AuthContext, error)) *Service
- func (s *Service) WithAsync(name string, handler AsyncHandler) *Service
- func (s *Service) WithAuthValidator(fn func(context.Context, *middleware.AuthContext, []string, []string) error) *Service
- func (s *Service) WithCRUD(model string, provider CRUDProvider) *Service
- func (s *Service) WithCRUDFactory(model string, factory CRUDFactory) *Service
- func (s *Service) WithCron(name string, handler CronJobFunc) *Service
- func (s *Service) WithExit(name string, h ExitHandler) *Service
- func (s *Service) WithExitHooks(h map[string]ExitHooks) *Service
- func (s *Service) WithFS(name string, fsys fs.FS) *Service
- func (s *Service) WithHandlers(h *EntryHandlers) *Service
- func (s *Service) WithHooks(model string, hooks any) *Service
- func (s *Service) WithJWTBlacklist(fn func(rawToken string) bool) *Service
- func (s *Service) WithOpenAPIMutator(fn SpecMutator) *Service
- func (s *Service) WithRateLimitMaxFunc(fn func(c *RestCtx) int) *Service
- func (s *Service) WithRest(name string, h func(*RestCtx) error) *Service
- func (s *Service) WithSSE(name string, h SSEHandler) *Service
- func (s *Service) WithScalarOptions(opts ...scalargo.Option) *Service
- func (s *Service) WithSeed(fn SeedFunc) *Service
- func (s *Service) WithWS(name string, h WSHandler) *Service
- type ServiceConfig
- type SlowQueryConf
- type SourceDef
- type SpecMutator
- type SpoolDef
- type StaticDef
- type StaticOption
- func StaticOptBrowse(v bool) StaticOption
- func StaticOptByteRange(v bool) StaticOption
- func StaticOptCompress(v bool) StaticOption
- func StaticOptDownload(v bool) StaticOption
- func StaticOptIndexNames(v ...string) StaticOption
- func StaticOptMaxAge(v int) StaticOption
- func StaticOptMethods(v ...string) StaticOption
- func StaticOptSPA(v bool) StaticOption
- type StorageDef
- type StreamConfig
- type StreamDef
- type SubscribeDef
- type TLSConf
- type TelemetryConf
- type TursoConf
- type WSHandler
Constants ¶
const ( TargetAuto = "auto" TargetVercel = "vercel" TargetDocker = "docker" TargetKube = "kube" TargetBare = "bare-metal" )
const NodeType = redis.NodeType
Variables ¶
var ErrNotFound = db.ErrNotFound
ErrNotFound is returned when a database record is not found.
Functions ¶
func BuildDirectTarget ¶ added in v0.11.0
func BuildEtcdTarget ¶ added in v0.11.0
func BuildOpenAPI ¶
BuildOpenAPI generates an OpenAPI 3.0.3 spec from the service config and registered models.
func BulkheadGet ¶ added in v0.11.0
func BulkheadRegister ¶ added in v0.11.0
func CachedCRUD ¶ added in v0.4.0
func CachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, keyPrefix string, l2TTL time.Duration, l1TTL time.Duration, )
CachedCRUD registers a CRUD provider with automatic L1 (memory) + L2 (Redis/Dragonfly) cache-aside. Cache is populated on miss using the DB primary key lookup. List/Create/Update/Delete return 405. The redisConf points to Dragonfly or Redis (NodeType or ClusterType). If l1TTL > 0, an in-process L1 cache (collection.Cache) is added in front of L2 for sub-μs reads.
func CheckScalarWarnings ¶ added in v0.19.0
func CheckScalarWarnings(cfg *ServiceConfig)
CheckScalarWarnings logs non-blocking warnings when Scalar UI is enabled but CORS or CSP are not configured for /docs. Scalar loads its assets from cdn.jsdelivr.net and Google Fonts; without the right CORS/CSP the docs page will render broken. The SDK never injects these for you — it is a user decision — so it warns and points to the reference example instead.
func CheckVercelWarnings ¶ added in v0.5.0
func CheckVercelWarnings(cfg *ServiceConfig)
CheckVercelWarnings logs non-blocking warnings for Vercel deployment.
func GenerateProto ¶ added in v0.15.0
func GenerateShortCode ¶ added in v0.13.0
GenerateShortCode generates a random alphanumeric string of given length. Uses crypto/rand for security-sensitive contexts (URL shorteners, tokens).
func GetTable ¶ added in v0.6.0
GetTable returns a typed *db.Table[T] for a model registered via MustRegister.
func GrpcCall ¶ added in v0.15.0
func GrpcCall[T any](ctx context.Context, gc *GrpcClient, fn func(conn ClientConnInterface) (T, error)) (T, error)
GrpcCall makes a typed gRPC call on the given client connection. Returns an error if the client is nil (not configured).
func InsertOutbox ¶ added in v0.13.0
InsertOutbox adds an event to the outbox table for transactional publishing. Called from within a DB transaction alongside the business logic write.
func InsertOutboxJSON ¶ added in v0.13.0
InsertOutboxJSON is a convenience wrapper for JSON payloads.
func IsSameOrigin ¶ added in v0.22.0
IsSameOrigin checks whether the given referer URL is same-origin with the request. This is the same check used by Back() internally. Exported for testing and custom redirect logic.
func MongoMustRegister ¶ added in v0.4.0
MongoMustRegister registers a CRUD provider for MongoDB backend. The model is lazily initialized on the first HTTP request. lookupField is the document field used for Get (e.g. "_id" or "short_code").
func MustGetGrpcServer ¶ added in v0.15.0
MustGetGrpcServer returns the gRPC server, or panics if gRPC is not available (server.mode must be "micro" with grpc_server.listen_on set).
func MustRegister ¶ added in v0.4.0
func MustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
MustRegister auto-creates the table and registers a CRUDProvider for the model. The pool, table, and hooks are lazily initialized on the first HTTP request.
func MySQLCachedCRUD ¶ added in v0.4.0
func MySQLCachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, keyPrefix string, l2TTL time.Duration, l1TTL time.Duration, )
MySQLCachedCRUD registers a CRUD provider with L1+L2 cache using MySQL as DB backend. Identical to CachedCRUD but uses *sql.DB and db.NewMySQLTable internally.
func MySQLMustRegister ¶ added in v0.4.0
func MySQLMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
MySQLMustRegister is like MustRegister but uses MySQL (*sql.DB) instead of PostgreSQL.
func PoolPGRead ¶ added in v0.14.0
PoolPGRead returns a read replica pool if available, falling back to write pool.
func PresignTTL ¶ added in v0.13.0
PresignTTL extracts the presign TTL duration from a StorageBackend. Returns 0 if the backend does not support presigned URLs.
func RegisterEntries ¶
func RegisterEntries(app *fiber.App, cfg *ServiceConfig, handlers *EntryHandlers, prefix string, brokers map[string]events.EventBroker, models map[string]*db.TableInfo, jwtCfg *middleware.JWTConfig, authValidator func(context.Context, *middleware.AuthContext, []string, []string) error, apiKeyValidator func(ctx context.Context, key string) (*middleware.AuthContext, error), fgaClient openfga.Checker, oryClient *ory.Client, zitadelClient *zitadel.Client, rlRdb ...*redis.Redis) error
func SanitizeFilename ¶ added in v0.1.0
func SetRateLimitMaxFunc ¶ added in v0.9.0
func TursoMustRegister ¶ added in v0.4.0
func TursoMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
TursoMustRegister registers a CRUD provider for Turso/SQLite backend.
func ValidateProjectStructure ¶ added in v0.5.0
ValidateProjectStructure checks that the project at yamlPath is structurally compatible with a given deploy target. Used by CLI commands. yamlPath is the path to service.yaml; the project root is derived from it.
func VerifyCallbackSignature ¶ added in v0.12.0
VerifyCallbackSignature verifies an HMAC-SHA256 signature for an async callback payload.
func WrapTransformHandler ¶
func WrapTransformHandler[T any](handler func(fiber.Ctx) error, hooks EntryHooks[T]) func(fiber.Ctx) error
WrapTransformHandler wraps a REST handler with BeforeTransform/AfterTransform hooks. The hooks must implement EntryHooks[T] where T is the request model. BeforeTransform parses the request body into T, calls the hook, stores the result in c.Locals("transformed"), then executes the handler. AfterTransform is called with the response body after the handler completes.
Usage:
svc.WithRest("onTransform", runtime.WrapTransformHandler(
func(c fiber.Ctx) error {
input := c.Locals("transformed").(Product)
return c.JSON(fiber.Map{"name": input.Name})
},
&ProductHooks{},
))
Types ¶
type APIKeyPrefillDef ¶ added in v0.25.0
type APIKeyPrefillDef struct {
// Name is the header/query/cookie name.
Name string `json:"name"`
// In selects where the key travels: header | query | cookie.
In string `json:"in" config:",default=header"`
// Token is the pre-filled key value (use ${VAR} for secrets).
Token string `json:"token" config:",optional"`
}
APIKeyPrefillDef describes an API key credential for the Try-It panel.
type AsyncCallbackConf ¶ added in v0.12.0
type AsyncCallbackConf struct {
// URL is the webhook endpoint called on job completion (required).
URL string `json:"url" config:",optional"`
// Secret is the HMAC key for signing the callback payload.
Secret string `json:"secret" config:",optional"`
// Retry is the number of retry attempts if the callback fails.
Retry int `json:"retry" config:",optional"`
// RetryDelay is the delay between retry attempts.
RetryDelay string `json:"retry_delay" config:",optional"`
}
AsyncCallbackConf configures a webhook to notify on job completion or failure.
type AsyncHandler ¶ added in v0.1.0
AsyncHandler is a function that processes an async job.
type AsyncJobManager ¶ added in v0.1.0
type AsyncJobManager struct {
// contains filtered or unexported fields
}
AsyncJobManager coordinates async job creation, processing, and status retrieval.
func NewAsyncJobManager ¶ added in v0.1.0
func NewAsyncJobManager(store JobStore, processor AsyncHandler) *AsyncJobManager
func NewAsyncJobManagerWithRetry ¶ added in v0.12.0
func NewAsyncJobManagerWithRetry(store JobStore, processor AsyncHandler, maxRetries int) *AsyncJobManager
func (*AsyncJobManager) HandleCancel ¶ added in v0.12.0
func (m *AsyncJobManager) HandleCancel() fiber.Handler
HandleCancel returns a Fiber handler for DELETE /path/:job_id requests.
func (*AsyncJobManager) HandleList ¶ added in v0.12.0
func (m *AsyncJobManager) HandleList() fiber.Handler
HandleList returns a Fiber handler for GET /path requests.
func (*AsyncJobManager) HandleStatus ¶ added in v0.1.0
func (m *AsyncJobManager) HandleStatus() fiber.Handler
HandleStatus returns a Fiber handler for GET /path/:job_id requests.
func (*AsyncJobManager) HandleStatusSSE ¶ added in v0.12.0
func (m *AsyncJobManager) HandleStatusSSE() fiber.Handler
HandleStatusSSE returns a Fiber handler for SSE streaming of job status changes.
func (*AsyncJobManager) HandleSubmit ¶ added in v0.1.0
func (m *AsyncJobManager) HandleSubmit() fiber.Handler
HandleSubmit returns a Fiber handler for POST requests that creates a job.
type AsyncReassignConf ¶ added in v0.12.0
type AsyncReassignConf struct {
// Enabled enables the background reaper goroutine.
Enabled bool `json:"enabled" config:",optional"`
// ProcessingTimeout is how long a job can stay in "processing" before being reaped.
// Default: 5m
ProcessingTimeout string `json:"processing_timeout" config:",optional"`
// ReapInterval is how often the reaper checks for stale jobs.
// Default: 30s
ReapInterval string `json:"reap_interval" config:",optional"`
// MaxRetries is the maximum number of times a job can be retried before moving to "failed".
// Default: 3
MaxRetries int `json:"max_retries" config:",optional"`
}
AsyncReassignConf configures automatic recovery of stuck processing jobs.
type AsyncStoreConf ¶ added in v0.12.0
type AsyncStoreConf struct {
// Driver selects the backend: "memory" (default), "postgres", "redis", "nats_kv".
Driver string `json:"driver" config:",optional"`
// DB references a database name for driver: postgres.
DB string `json:"db" config:",optional"`
// KV references a kv store name for driver: redis.
KV string `json:"kv" config:",optional"`
// Stream references a stream name for driver: nats_kv.
Stream string `json:"stream" config:",optional"`
// Bucket is the NATS KV bucket name (driver: nats_kv).
Bucket string `json:"bucket" config:",optional"`
// Table is the PostgreSQL table name (driver: postgres).
Table string `json:"table" config:",optional"`
// Reassign configures automatic recovery of stuck jobs (reaper).
Reassign *AsyncReassignConf `json:"reassign" config:",optional"`
// Callback configures a webhook to notify on job completion.
Callback *AsyncCallbackConf `json:"callback" config:",optional"`
// ResultTTL is how long completed/failed jobs are kept before cleanup.
// Default: 0 (keep forever)
ResultTTL string `json:"result_ttl" config:",optional"`
// MaxConcurrent limits the number of jobs processed simultaneously.
// Default: 0 (unlimited)
MaxConcurrent int `json:"max_concurrent" config:",optional"`
}
AsyncStoreConf configures the job store backend for async entries.
type AuthConfig ¶ added in v0.1.1
type AuthConfig struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",optional"`
// Driver is a constant.
Driver string `json:"driver" config:",default=none"` // none | manual | openfga-zitadel | ory
// Secret is a constant.
Secret string `json:"secret" config:",optional"`
// PrevSecret is a constant.
PrevSecret string `json:"prev_secret" config:",optional"`
// Algorithm is a constant.
Algorithm string `json:"algorithm" config:",default=HS256"`
// JWKSURL enables RS256 validation against a remote JWKS endpoint
// (e.g. an OAuth server's /.well-known/jwks.json) with kid-based rotation.
JWKSURL string `json:"jwks_url" config:",optional"`
// ContextKey is a constant.
ContextKey string `json:"context_key" config:",default=claims"`
// Issuer is a constant.
Issuer string `json:"issuer" config:",optional"`
// Audience is a constant.
Audience string `json:"audience" config:",optional"`
// Expiry is a constant.
Expiry int `json:"expiry" config:",default=900"` // JWT TTL in seconds (default 15 min)
// ZitadelURL is a constant.
ZitadelURL string `json:"zitadel_url" config:",optional"`
// OpenFGAURL is a constant.
OpenFGAURL string `json:"openfga_url" config:",optional"`
// OpenFGAStore is a constant.
OpenFGAStore string `json:"openfga_store" config:",optional"`
// KratosURL is a constant.
KratosURL string `json:"kratos_url" config:",optional"`
// KetoURL is a constant.
KetoURL string `json:"keto_url" config:",optional"`
// Refresh is a constant.
Refresh *RefreshConfig `json:"refresh" config:",optional"`
// Cookie is a constant.
Cookie *AuthCookieConfig `json:"cookie" config:",optional"`
}
type AuthCookieConfig ¶ added in v0.9.0
type AuthCookieConfig struct {
// AccessTokenName is a constant.
AccessTokenName string `json:"access_token_name" config:",default=token"`
// RefreshTokenName is a constant.
RefreshTokenName string `json:"refresh_token_name" config:",default=refresh_token"`
// Domain is a constant.
Domain string `json:"domain" config:",optional"`
// Path is a constant.
Path string `json:"path" config:",default=/"`
// HTTPOnly is a constant.
HTTPOnly bool `json:"http_only" config:",default=true"`
// Secure is a constant.
Secure bool `json:"secure" config:",default=true"`
// SameSite is a constant.
SameSite string `json:"same_site" config:",default=Strict"`
}
type AuthPrefillDef ¶ added in v0.25.0
type AuthPrefillDef struct {
// PreferredScheme names the security scheme selected by default.
PreferredScheme string `json:"preferred_scheme" config:",optional"`
// BearerToken prefills the HTTP bearer token.
BearerToken string `json:"bearer_token" config:",optional"`
// APIKey prefills an API key credential.
APIKey *APIKeyPrefillDef `json:"api_key" config:",optional"`
}
AuthPrefillDef prefills the Try-It authentication panel.
type AutocertTLS ¶ added in v0.1.0
type CORSConf ¶
type CORSConf struct {
// Origins is a constant.
Origins []string `json:"origins" config:",optional"`
// Methods is a constant.
Methods []string `json:"methods" config:",optional"`
// Headers is a constant.
Headers []string `json:"headers" config:",optional"`
// Credentials is a constant.
Credentials bool `json:"credentials" config:",optional"`
// MaxAge is a constant.
MaxAge int `json:"max_age" config:",default=300"`
// ExposeHeaders is a constant.
ExposeHeaders []string `json:"expose_headers" config:",optional"`
// AllowPrivateNetwork is a constant.
AllowPrivateNetwork bool `json:"allow_private_network" config:",optional"`
}
type CORSGroupConf ¶ added in v0.19.0
type CORSGroupConf struct {
// Name is the unique group name referenced by entry[].cors or middleware cors:<name>.
Name string `json:"name"`
// Origins is a constant.
Origins []string `json:"origins" config:",optional"`
// Methods is a constant.
Methods []string `json:"methods" config:",optional"`
// Headers is a constant.
Headers []string `json:"headers" config:",optional"`
// Credentials is a constant.
Credentials bool `json:"credentials" config:",optional"`
// MaxAge is a constant.
MaxAge int `json:"max_age" config:",default=300"`
// ExposeHeaders is a constant.
ExposeHeaders []string `json:"expose_headers" config:",optional"`
// AllowPrivateNetwork is a constant.
AllowPrivateNetwork bool `json:"allow_private_network" config:",optional"`
}
CORSGroupConf is a named CORS policy that routes can reference by name.
type CRUDFactory ¶ added in v0.3.1
type CRUDFactory func() CRUDProvider
CRUDFactory creates a CRUDProvider when needed (lazy initialization). Use WithCRUDFactory instead of WithCRUD when the provider depends on resources initialized during Run() (e.g., database pools).
type CRUDOverrides ¶
type CRUDOverrides struct {
// List is a constant.
List string `json:"list" config:",optional"`
// Get is a constant.
Get string `json:"get" config:",optional"`
// Create is a constant.
Create string `json:"create" config:",optional"`
// Update is a constant.
Update string `json:"update" config:",optional"`
// Delete is a constant.
Delete string `json:"delete" config:",optional"`
}
type CRUDProvider ¶
type CRUDProvider interface {
List(ctx fiber.Ctx, params ListParams) error
Get(ctx fiber.Ctx, id string) error
Create(ctx fiber.Ctx, body []byte) error
Update(ctx fiber.Ctx, id string, body []byte) error
Delete(ctx fiber.Ctx, id string) error
}
func NewCRUDProvider ¶
func NewCRUDProvider[T any](table *db.Table[T], hooks EntryHooks[T]) CRUDProvider
NewCRUDProvider wraps a db.Table[T] (PostgreSQL) into a CRUDProvider.
func NewMongoCRUDProvider ¶ added in v0.4.0
func NewMongoCRUDProvider(model *mon.Model, lookupField string) CRUDProvider
NewMongoCRUDProvider creates a CRUDProvider backed by MongoDB. lookupField is the document field used for Get/Update/Delete (e.g. "_id" or "short_code").
func NewMySQLCRUDProvider ¶
func NewMySQLCRUDProvider[T any](table *db.MySQLTable[T], hooks EntryHooks[T]) CRUDProvider
func NewTursoCRUDProvider ¶
func NewTursoCRUDProvider[T any](table *db.TursoTable[T], hooks EntryHooks[T]) CRUDProvider
type CSPConf ¶ added in v0.9.0
type CSPConf struct {
// Level is a constant.
Level string `json:"level" config:",default=basic"`
// DefaultSrc is a constant.
DefaultSrc []string `json:"default_src" config:",optional"`
// ScriptSrc is a constant.
ScriptSrc []string `json:"script_src" config:",optional"`
// StyleSrc is a constant.
StyleSrc []string `json:"style_src" config:",optional"`
// ImgSrc is a constant.
ImgSrc []string `json:"img_src" config:",optional"`
// ConnectSrc is a constant.
ConnectSrc []string `json:"connect_src" config:",optional"`
// FontSrc is a constant.
FontSrc []string `json:"font_src" config:",optional"`
// FrameSrc is a constant.
FrameSrc []string `json:"frame_src" config:",optional"`
// FrameAncestors is a constant.
FrameAncestors []string `json:"frame_ancestors" config:",optional"`
// ObjectSrc is a constant.
ObjectSrc []string `json:"object_src" config:",optional"`
// BaseURI is a constant.
BaseURI []string `json:"base_uri" config:",optional"`
// FormAction is a constant.
FormAction []string `json:"form_action" config:",optional"`
// UpgradeInsecureReq is a constant.
UpgradeInsecureReq bool `json:"upgrade_insecure_requests" config:",optional"`
}
type CSPGroupConf ¶ added in v0.19.3
type CSPGroupConf struct {
// Name is the unique group name referenced by entry[].csp or middleware csp:<name>.
Name string `json:"name"`
// CSPConfig is the per-route CSP policy (same shape as security_headers.csp_config).
CSPConfig *CSPConf `json:"csp_config" config:",optional"`
}
CSPGroupConf is a named per-route Content-Security-Policy, referenced by entry[].csp or middleware[].apply "csp:<name>". It overrides the global CSP.
type CSRFConf ¶ added in v0.1.0
type CSRFConf struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",optional"`
// CookieName is a constant.
CookieName string `json:"cookie_name" config:",optional"`
// HeaderName is a constant.
HeaderName string `json:"header_name" config:",optional"`
// SameSite is a constant.
SameSite string `json:"same_site" config:",optional"`
// Secure is a constant.
Secure bool `json:"secure" config:",optional"`
// ExcludePaths is a constant.
ExcludePaths []string `json:"exclude_paths" config:",optional"`
// JSONCheck is a constant.
JSONCheck bool `json:"json_check" config:",optional"`
}
type CacheConfig ¶ added in v0.6.0
type CacheConfig struct {
// L1 is a constant.
L1 string `json:"l1" config:",default=ram"` // ram | none
// L1TTL is a constant.
L1TTL string `json:"l1_ttl" config:",default=5m"`
// L1Size is a constant.
L1Size int `json:"l1_size" config:",default=10000"`
// L2 is a constant.
L2 string `json:"l2" config:",optional"` // disk | none
// L2Path is a constant.
L2Path string `json:"l2_path" config:",optional"`
}
type ClientConnInterface ¶ added in v0.15.0
type ClientConnInterface = grpc.ClientConnInterface
ClientConnInterface is a type alias for grpc.ClientConnInterface, exported so example projects can reference the type without importing grpc directly.
func MustGetGrpcClientConn ¶ added in v0.15.0
func MustGetGrpcClientConn(svc *Service, name string) ClientConnInterface
MustGetGrpcClientConn returns the gRPC client connection for a named client. Returns nil if the client is not configured.
type ContentSecurityDef ¶ added in v0.2.0
type Cookie ¶ added in v0.9.0
type Cookie struct {
Name string
Value string
Path string
Domain string
MaxAge int
HTTPOnly bool
Secure bool
SameSite string
}
Cookie configures an HTTP cookie set by the SDK.
type CookieConf ¶ added in v0.1.0
type CorrelationConf ¶ added in v0.11.0
type CorrelationConf struct {
// Enabled enables the correlation ID middleware.
Enabled bool `json:"enabled" config:",optional"`
// RequestHeader is the header to read the correlation ID from.
RequestHeader string `json:"request_header" config:",default=X-Correlation-ID"`
// ResponseHeader is the header to set the correlation ID on.
ResponseHeader string `json:"response_header" config:",default=X-Correlation-ID"`
// SkipPaths are request paths that should not receive a correlation ID.
SkipPaths []string `json:"skip_paths" config:",optional"`
}
type CronJob ¶
type CronJob struct {
// Name is a constant.
Name string `json:"name"`
// Schedule is a constant.
Schedule string `json:"schedule"`
// Mode is a constant.
Mode string `json:"mode" config:",default=nats"` // nats, handler, internal
// Publish is a constant.
Publish *CronPublish `json:"publish" config:",optional"`
// Handler is a constant.
Handler string `json:"handler" config:",optional"`
}
type CronJobFunc ¶
type CronPublish ¶
type CronScheduler ¶
type CronScheduler struct {
// contains filtered or unexported fields
}
func NewCronScheduler ¶
func NewCronScheduler() *CronScheduler
func (*CronScheduler) AddAll ¶
func (s *CronScheduler) AddAll(ctx context.Context, cronDefs []CronJob, brokers map[string]events.EventBroker, handlers map[string]CronJobFunc) error
func (*CronScheduler) AddJob ¶
func (s *CronScheduler) AddJob(ctx context.Context, cfg CronJob, broker events.EventBroker, handler CronJobFunc) error
func (*CronScheduler) Start ¶
func (s *CronScheduler) Start()
func (*CronScheduler) Stop ¶
func (s *CronScheduler) Stop()
type CryptionDef ¶ added in v0.2.0
type DBConfig ¶
type DBConfig struct {
// Name is a constant.
Name string `json:"name"`
// Driver is a constant.
Driver string `json:"driver" config:",default=postgres"`
// URL is a constant.
URL string `json:"url"`
// AuthToken is the auth token for remote Turso/libSQL drivers
// (turso-serverless, libsql, go-libsql sync). Supports ${VAR} from env.
AuthToken string `json:"auth_token" config:",optional"`
// ReadURL is the read replica connection URL for read/write splitting.
ReadURL string `json:"read_url" config:",optional"`
// Database is a constant.
Database string `json:"database" config:",optional"`
// Pool is a constant.
Pool *PoolConf `json:"pool" config:",optional"`
// Turso is a constant.
Turso *TursoConf `json:"turso" config:",optional"`
// SlowQuery is a constant.
SlowQuery *SlowQueryConf `json:"slow_query" config:",optional"`
}
type DefaultExitHooks ¶
type DefaultExitHooks struct{}
func (DefaultExitHooks) OnSuccess ¶
func (DefaultExitHooks) OnSuccess(_ context.Context)
type DefaultHooks ¶
type DefaultHooks[T any] struct{}
func (DefaultHooks[T]) AfterCreate ¶
func (DefaultHooks[T]) AfterCreate(_ context.Context, _ *T) error
func (DefaultHooks[T]) AfterDelete ¶
func (DefaultHooks[T]) AfterDelete(_ context.Context, _ string) error
func (DefaultHooks[T]) AfterTransform ¶
func (DefaultHooks[T]) AfterTransform(_ context.Context, _ any) error
func (DefaultHooks[T]) AfterUpdate ¶
func (DefaultHooks[T]) AfterUpdate(_ context.Context, _ *T) error
func (DefaultHooks[T]) BeforeCreate ¶
func (DefaultHooks[T]) BeforeCreate(_ context.Context, req T) (T, error)
func (DefaultHooks[T]) BeforeDelete ¶
func (DefaultHooks[T]) BeforeDelete(_ context.Context, _ string) error
func (DefaultHooks[T]) BeforeTransform ¶
func (DefaultHooks[T]) BeforeTransform(_ context.Context, req T) (T, error)
type DeployConfig ¶ added in v0.5.0
type DeployConfig struct {
// Target is a constant.
Target string `json:"target" config:",default=auto"`
}
type DocsHooks ¶ added in v0.25.0
type DocsHooks struct {
// Mutators run in registration order on the generated spec.
Mutators []SpecMutator
// ScalarOptions are appended to the options built from the YAML config.
ScalarOptions []scalargo.Option
}
DocsHooks carries the Service-level OpenAPI hooks into registerDocs.
type EncryptCookieDef ¶ added in v0.8.0
type EntryDef ¶
type EntryDef struct {
// Type is a constant.
Type string `json:"type"` // crud, rest, webhook, websocket, sse, file
// Method is a constant.
Method string `json:"method" config:",optional"`
// Path is a constant.
Path string `json:"path" config:",optional"`
// Handler is a constant.
Handler string `json:"handler" config:",optional"`
// Summary documents the operation in the OpenAPI spec (one line).
Summary string `json:"summary" config:",optional"`
// Description documents the operation in the OpenAPI spec (long form).
Description string `json:"description" config:",optional"`
// AuthModes is a constant.
AuthModes []string `json:"auth_modes" config:",optional"` // ["jwt"], ["apikey"], ["jwt","apikey"]
// JWTFrom is a constant.
JWTFrom string `json:"jwt_from" config:",optional"` // per-entry: "header:Authorization", "cookie:token", "query:token"
// Roles is a constant.
Roles []string `json:"roles" config:",optional"`
// Permissions is a constant.
Permissions []string `json:"permissions" config:",optional"`
// DB is a constant.
DB string `json:"db" config:",optional"` // references database name
// CORS references a named cors_groups[].name policy for this entry.
// Empty means the server-level CORS (or none) applies.
CORS string `json:"cors" config:",optional"`
// CSP references a named csp_groups[].name policy for this entry.
// Empty means the global security_headers CSP applies.
CSP string `json:"csp" config:",optional"`
// TenantScope is a constant.
TenantScope string `json:"tenant_scope" config:",optional"` // JWT claim for tenant ID (e.g. "org_id")
// TenantField is a constant.
TenantField string `json:"tenant_field" config:",optional"` // DB column for tenant filter (e.g. "tenant_id")
// ServiceName is the gRPC service name (required for type: grpc).
ServiceName string `json:"service_name" config:",optional"`
// CRUD
Model string `json:"model" config:",optional"`
// Table is a constant.
Table string `json:"table" config:",optional"`
// Resource is a constant.
Resource string `json:"resource" config:",optional"`
// Overrides is a constant.
Overrides *CRUDOverrides `json:"overrides" config:",optional"`
// Event stream selection
EventStream string `json:"event_stream" config:",optional"`
// Event publish targets
EventPublish []EventPublishTarget `json:"event_publish" config:",optional"`
// File
AllowedTypes []string `json:"allowed_types" config:",optional"`
// MaxSize is a constant.
MaxSize string `json:"max_size" config:",optional"`
// MaxFiles is a constant.
MaxFiles int `json:"max_files" config:",optional"`
// MagicBytes is a constant.
MagicBytes bool `json:"magic_bytes" config:",optional"`
// Storage is a constant.
Storage *StorageDef `json:"storage" config:",optional"`
// Security per-entry overrides
CSRF *bool `json:"csrf" config:",optional"` // false = skip CSRF for this entry
// RequiresMFA is a constant.
RequiresMFA bool `json:"requires_mfa" config:",optional"` // true = MFA must be verified
// RateLimit is a constant.
RateLimit *RateLimitDef `json:"rate_limit" config:",optional"` // per-entry rate limit (pre-auth)
// RateLimitPerUser is a constant.
RateLimitPerUser *RateLimitDef `json:"rate_limit_per_user" config:",optional"` // per-entry per-user rate limit (post-auth)
// RateLimitPerKey is a constant.
RateLimitPerKey *RateLimitDef `json:"rate_limit_per_key" config:",optional"` // per-entry per-key rate limit (post-auth)
// PerRoleLimits is a constant.
PerRoleLimits map[string]*RateLimitDef `json:"rate_limit_per_role" config:",optional"` // per-role rate limits
// Cache is a constant.
Cache string `json:"cache" config:",optional"` // references kv[].name for CRUD cache
// Validation
ValidationModel string `json:"validate" config:",optional"` // validation model name
// APIVersion sets the API version prefix for this entry (e.g. "v1", "v2").
// If empty and the server api_prefix does not already contain a version,
// defaults to "v1".
APIVersion string `json:"api_version" config:",optional"`
// APIStatus indicates the lifecycle status of this endpoint.
// Values: current | deprecated | removed
APIStatus string `json:"api_status" config:",optional"`
// SunsetDate is the RFC3339 date when the endpoint will be removed.
SunsetDate string `json:"sunset_date" config:",optional"`
// Timeout per-entry (e.g. "30s")
Timeout string `json:"timeout" config:",optional"`
// Retry configures the retry behavior for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS).
Retry *RetryConf `json:"retry" config:",optional"`
// Fallback sets the fallback strategy when the circuit breaker is open.
// Values: "degraded" | "stale" | "" (disabled)
Fallback string `json:"fallback" config:",optional"`
// Bulkhead defines named concurrency limits for external outbound calls.
// Each key is a dependency name, value is max concurrent calls.
Bulkhead map[string]int `json:"bulkhead" config:",optional"`
// API Key prefix (only applies when auth_modes includes "apikey")
APIPrefix string `json:"api_key_prefix" config:",optional"`
// Pagination (CRUD only)
PageSize int `json:"page_size" config:",optional"` // default 10, also min
// MaxPageSize is a constant.
MaxPageSize int `json:"max_page_size" config:",optional"` // default 100, also max
// Pagination is a constant.
Pagination string `json:"pagination" config:",optional"` // "offset" | "keyset"
// Sortable is a constant.
Sortable []string `json:"sortable" config:",optional"` // allowed sort columns
// AsyncStore configures the job store backend for type: async entries.
AsyncStore *AsyncStoreConf `json:"async_store" config:",optional"`
}
type EntryHandlers ¶
type EntryHandlers struct {
Rest map[string]func(fiber.Ctx) error
WS map[string]WSHandler
SSE map[string]SSEHandler
CRUD map[string]CRUDProvider
Storage map[string]server.StorageBackend
Async map[string]AsyncHandler
Transform map[string]any
Reapers []*Reaper
}
type EntryHooks ¶
type EntryHooks[T any] interface { BeforeCreate(ctx context.Context, req T) (T, error) AfterCreate(ctx context.Context, entity *T) error BeforeUpdate(ctx context.Context, id string, patch map[string]any) (map[string]any, error) AfterUpdate(ctx context.Context, entity *T) error BeforeDelete(ctx context.Context, id string) error AfterDelete(ctx context.Context, id string) error BeforeTransform(ctx context.Context, req T) (T, error) AfterTransform(ctx context.Context, result any) error }
EntryHooks defines lifecycle callbacks for entry endpoints (HTTP).
type EventPublishTarget ¶ added in v0.1.0
type EventStreamConnConf ¶ added in v0.1.0
type EventStreamConnConf struct {
// Name is a constant.
Name string `json:"name"`
// Driver is a constant.
Driver string `json:"driver"` // nats, kafka
// URL is a constant.
URL string `json:"url" config:",optional"`
// Brokers is a constant.
Brokers []string `json:"brokers" config:",optional"`
// ConsumerGroup is a constant.
ConsumerGroup string `json:"consumer_group" config:",optional"`
// MaxReconnects is a constant.
MaxReconnects int `json:"max_reconnects" config:",optional"`
// ReconnectWait is a constant.
ReconnectWait string `json:"reconnect_wait" config:",optional"`
// Timeout is a constant.
Timeout string `json:"timeout" config:",optional"`
// RetryOnFail is a constant.
RetryOnFail bool `json:"retry_on_fail" config:",optional"`
// Streams is a constant.
Streams []StreamDef `json:"streams" config:",optional"`
}
func (*EventStreamConnConf) Validate ¶ added in v0.1.0
func (e *EventStreamConnConf) Validate() error
type ExitHooks ¶
type ExitHooks interface {
OnMessage(ctx context.Context, msg []byte) ([]byte, error)
OnSuccess(ctx context.Context)
OnError(ctx context.Context, err error)
}
ExitHooks defines lifecycle callbacks for exit workers (NATS).
type ExitWorker ¶
type ExitWorker struct {
// Name is a constant.
Name string `json:"name"`
// Subscribe is a constant.
Subscribe SubscribeDef `json:"subscribe"`
// Handler is a constant.
Handler string `json:"handler"`
// MaxConcurrent is a constant.
MaxConcurrent int `json:"max_concurrent" config:",default=1"`
// DB is a constant.
DB string `json:"db" config:",optional"`
// Reply is a constant.
Reply bool `json:"reply" config:",optional"`
// ReplyTimeout is a constant.
ReplyTimeout string `json:"reply_timeout" config:",default=30s"`
// PullBatch is a constant.
PullBatch int `json:"pull_batch" config:",optional"`
// PullMaxWait is a constant.
PullMaxWait string `json:"pull_max_wait" config:",optional"`
// ConsumerMode is a constant.
ConsumerMode string `json:"consumer_mode" config:",optional"` // push or pull
// EventStream is a constant.
EventStream string `json:"event_stream" config:",optional"` // broker name
// TermOnFailure terminates (DLQ) instead of Nak when handler returns error.
TermOnFailure bool `json:"term_on_failure" config:",optional"`
}
func (*ExitWorker) Validate ¶
func (e *ExitWorker) Validate() error
type ExitWorkerManager ¶
type ExitWorkerManager struct {
// contains filtered or unexported fields
}
func NewExitWorkerManager ¶
func NewExitWorkerManager() *ExitWorkerManager
func (*ExitWorkerManager) Shutdown ¶
func (m *ExitWorkerManager) Shutdown(timeout time.Duration)
func (*ExitWorkerManager) Start ¶
func (m *ExitWorkerManager) Start(ctx context.Context, exitDefs []ExitWorker, brokers map[string]events.EventBroker, handlers map[string]ExitHandler, hooks map[string]ExitHooks) error
type FlashMessage ¶ added in v0.22.0
FlashMessage holds a key-value flash message with an optional severity level.
type GCConfig ¶ added in v0.14.0
type GCConfig struct {
// GOGC sets the GC target percentage. Default 100. Higher = less GC, more memory.
// Set to 200 for higher throughput at the cost of ~2x memory.
GOGC int `json:"go_gc" config:",default=100"`
// MemoryLimit sets GOMEMLIMIT. Can be a percentage of container memory (e.g. "80%")
// or an absolute value (e.g. "2GiB", "512MiB"). Empty means no limit.
MemoryLimit string `json:"memory_limit" config:",optional"`
}
GCConfig configures Go runtime garbage collection parameters.
type GrpcClient ¶ added in v0.11.0
type GrpcClient struct {
// contains filtered or unexported fields
}
func NewGrpcClient ¶ added in v0.11.0
func NewGrpcClient(cfg *GrpcClientConf) (*GrpcClient, error)
func (*GrpcClient) Close ¶ added in v0.11.0
func (gc *GrpcClient) Close() error
func (*GrpcClient) Conn ¶ added in v0.11.0
func (gc *GrpcClient) Conn() *grpc.ClientConn
func (*GrpcClient) Name ¶ added in v0.11.0
func (gc *GrpcClient) Name() string
type GrpcClientConf ¶ added in v0.11.0
type GrpcClientConf struct {
// Name is a unique name for this client connection.
Name string `json:"name"`
// Target is the gRPC target address (e.g. "dns:///product-svc:8081").
Target string `json:"target" config:",optional"`
// Secure enables TLS transport credentials instead of insecure.
Secure bool `json:"secure" config:",optional"`
// Endpoints are direct gRPC endpoints (e.g. ["localhost:8081"]).
Endpoints []string `json:"endpoints" config:",optional"`
// Timeout is the default RPC timeout in milliseconds.
Timeout int64 `json:"timeout" config:",default=2000"`
// NonBlock enables non-blocking dial.
NonBlock bool `json:"non_block" config:",default=true"`
}
type GrpcInterceptorsConfig ¶ added in v0.11.0
type GrpcRegisterFn ¶ added in v0.11.0
type GrpcServer ¶ added in v0.11.0
type GrpcServer struct {
// contains filtered or unexported fields
}
func NewGrpcServer ¶ added in v0.11.0
func NewGrpcServer(cfg *GrpcServerConf, register GrpcRegisterFn, interceptorCfg ...GrpcInterceptorsConfig) (*GrpcServer, error)
func (*GrpcServer) Server ¶ added in v0.11.0
func (gs *GrpcServer) Server() *grpc.Server
func (*GrpcServer) Start ¶ added in v0.11.0
func (gs *GrpcServer) Start()
func (*GrpcServer) Stop ¶ added in v0.11.0
func (gs *GrpcServer) Stop()
type GrpcServerConf ¶ added in v0.11.0
type GrpcServerConf struct {
// ListenOn is the address to listen on (e.g. ":8081").
ListenOn string `json:"listen_on" config:",optional"`
// Timeout is the default RPC timeout in milliseconds.
Timeout int64 `json:"timeout" config:",default=2000"`
// CpuThreshold is the CPU load threshold for adaptive shedding (0-1000). 0 disables.
CpuThreshold int64 `json:"cpu_threshold" config:",default=900"`
// Health enables the gRPC health check service.
Health bool `json:"health" config:",default=true"`
// EtcdEndpoints are the etcd cluster hosts for service registration (micro mode).
EtcdEndpoints []string `json:"etcd_endpoints" config:",optional"`
// EtcdKey is the service key to register in etcd (e.g. "user-svc").
EtcdKey string `json:"etcd_key" config:",optional"`
}
type HTTPClientDef ¶ added in v0.25.0
type HTTPClientDef struct {
// Target is the language/platform key (e.g. "node", "php", "python").
Target string `json:"target" config:",optional"`
// Client is the client library key (e.g. "undici", "guzzle", "requests").
Client string `json:"client" config:",optional"`
}
HTTPClientDef pins the default Try-It HTTP client for the docs UI.
type JobState ¶ added in v0.1.0
type JobState struct {
ID string `json:"id"`
Status JobStatus `json:"status"`
Result any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
RetryCount int `json:"retry_count,omitempty"`
MaxRetries int `json:"max_retries,omitempty"`
ProcessingDeadline *time.Time `json:"processing_deadline,omitempty"`
CallbackURL string `json:"callback_url,omitempty"`
}
JobState holds the state and result of an async job.
type JobStatus ¶ added in v0.1.0
type JobStatus string
JobStatus represents the processing state of a job.
type JobStore ¶ added in v0.1.0
type JobStore interface {
Create(id string) *JobState
Get(id string) (*JobState, bool)
// Snapshot returns a defensive copy of a job state, safe to serialize
// outside the store lock (HTTP handlers). Mutating it does not persist.
Snapshot(id string) (*JobState, bool)
Update(id string, status JobStatus, result any, errMsg string)
Delete(id string)
// List returns all jobs (best-effort, limited).
List() ([]*JobState, error)
// ReapStale resets jobs stuck in "processing" for longer than the deadline.
// Returns the number of jobs reaped.
ReapStale(ctx context.Context, timeout time.Duration, maxRetries int) (int, error)
// Cleanup removes completed and failed jobs older than ttl.
// Returns the number of jobs cleaned.
Cleanup(ctx context.Context, ttl time.Duration) (int, error)
}
JobStore persists and retrieves job state.
type KVConfig ¶ added in v0.9.0
type KVConfig struct {
// Name is a constant.
Name string `json:"name"`
// Driver is a constant.
Driver string `json:"driver" config:",default=redis"`
// URL is a constant.
URL string `json:"url"`
// PoolSize is the redis connection pool size. 0 uses the go-redis default (10 * GOMAXPROCS).
PoolSize int `json:"pool_size" config:",optional"`
}
type KeysetResponse ¶ added in v0.6.0
type KeysetResponse struct {
Data any `json:"data"`
NextCursor string `json:"nextCursor,omitempty"`
PageSize int `json:"pageSize"`
}
KeysetResponse is used by tableCRUD.List (keyset mode).
type ListParams ¶
type OldInputData ¶ added in v0.22.0
OldInputData holds a key-value pair from a previous form submission.
type OpenAPIConf ¶
type OpenAPIConf struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",optional"`
// Version is a constant.
Version string `json:"version" config:",default=1.0.0"`
// SpecPath is a constant.
SpecPath string `json:"spec_path" config:",default=/openapi.json"`
// DocsPath is a constant.
DocsPath string `json:"docs_path" config:",default=/docs"`
// Theme is a constant.
Theme string `json:"theme" config:",default=moon"`
// DarkMode is a constant.
DarkMode bool `json:"dark_mode" config:",default=true"`
// SpecCacheTTL sets Cache-Control max-age for /openapi.json
SpecCacheTTL string `json:"spec_cache_ttl" config:",default=1h"`
// FaviconURL sets a custom favicon for the docs page. It accepts:
// "" (empty) → inline SVG magnifying glass
// "path/to/x.svg" → file on disk (relative to working dir, read once)
// "https://..." → remote URL, downloaded server-side with TTL cache
FaviconURL string `json:"favicon_url" config:",optional"`
// FaviconRefresh is the cache TTL for remote favicons (e.g. "24h").
// Defaults to 24h. Only used when favicon_url is an http(s) URL.
FaviconRefresh string `json:"favicon_refresh" config:",default=24h"`
// Title overrides the docs page title (defaults to the service name).
Title string `json:"title" config:",optional"`
// Description sets info.description in the generated spec and the docs page.
Description string `json:"description" config:",optional"`
// Layout selects the Scalar layout: "modern" or "classic" (default modern).
Layout string `json:"layout" config:",optional"`
// ForceDarkMode locks the docs UI to dark mode regardless of system theme.
ForceDarkMode bool `json:"force_dark_mode" config:",optional"`
// HideDarkModeToggle removes the light/dark switch from the docs UI.
HideDarkModeToggle bool `json:"hide_dark_mode_toggle" config:",optional"`
// CustomCSS injects brand CSS (e.g. --scalar-* variables) into the docs page.
CustomCSS string `json:"custom_css" config:",optional"`
// CustomHeadJS injects a script into the docs page <head>.
CustomHeadJS string `json:"custom_head_js" config:",optional"`
// CustomBodyJS injects a script right before the docs page </body>.
CustomBodyJS string `json:"custom_body_js" config:",optional"`
// HideDownload removes the "Download OpenAPI spec" button.
HideDownload bool `json:"hide_download" config:",optional"`
// HideModels hides the schema/model section from the docs UI.
HideModels bool `json:"hide_models" config:",optional"`
// HideSearch disables the docs search bar.
HideSearch bool `json:"hide_search" config:",optional"`
// Sidebar toggles the navigation sidebar (default true).
Sidebar *bool `json:"sidebar" config:",optional"`
// ShowToolbar controls the developer toolbar: always | localhost | never.
ShowToolbar string `json:"show_toolbar" config:",optional"`
// SearchHotKey sets the search keyboard shortcut key (default "k").
SearchHotKey string `json:"search_hot_key" config:",optional"`
// Editable lets users edit the spec live in the docs UI.
Editable bool `json:"editable" config:",optional"`
// TagsSorter sorts tag groups: alpha (empty preserves spec order).
TagsSorter string `json:"tags_sorter" config:",optional"`
// OperationsSorter sorts operations: alpha | method.
OperationsSorter string `json:"operations_sorter" config:",optional"`
// OperationTitleSource picks operation titles: summary | path.
OperationTitleSource string `json:"operation_title_source" config:",optional"`
// OrderSchemaPropertiesBy orders schema properties: alpha | preserve.
OrderSchemaPropertiesBy string `json:"order_schema_properties_by" config:",optional"`
// PersistAuth keeps Try-It credentials across page reloads.
PersistAuth bool `json:"persist_auth" config:",optional"`
// DefaultHTTPClient pins the Try-It client: {target, client}.
DefaultHTTPClient *HTTPClientDef `json:"default_http_client" config:",optional"`
// HiddenClients hides Try-It client entries (e.g. [postman]).
HiddenClients []string `json:"hidden_clients" config:",optional"`
// CDN overrides the Scalar asset CDN (default jsdelivr).
CDN string `json:"cdn" config:",optional"`
// Proxy routes Try-It requests through a CORS proxy.
Proxy string `json:"proxy" config:",optional"`
// BaseServerURL pins the server URL used by Try-It requests.
BaseServerURL string `json:"base_server_url" config:",optional"`
// ServersOverride replaces the spec servers list in the docs UI.
ServersOverride []ServerOverrideDef `json:"servers_override" config:",optional"`
// Sources renders multiple OpenAPI documents as docs tabs.
Sources []SourceDef `json:"sources" config:",optional"`
// Auth prefills the Try-It authentication panel.
Auth *AuthPrefillDef `json:"auth" config:",optional"`
// CSPConnect adds extra connect-src hosts so Try It can reach the APIs.
CSPConnect []string `json:"csp_connect" config:",optional"`
}
type OutboxRecord ¶ added in v0.13.0
type OutboxRecord struct {
ID int64 `db:"id,primary,auto"`
Subject string `db:"subject,required"`
Payload string `db:"payload,required"`
Status string `db:"status,required,default='pending'"`
CreatedAt string `db:"created_at,default=now()"`
}
OutboxRecord represents a pending event in the outbox table.
type OutboxRelay ¶ added in v0.13.0
type OutboxRelay struct {
// contains filtered or unexported fields
}
OutboxRelay polls the outbox table and publishes pending events to NATS. It runs in a background goroutine and is opt-in via event_publish.outbox: true.
func NewOutboxRelay ¶ added in v0.13.0
func NewOutboxRelay(pool *pgxpool.Pool, broker events.EventBroker) (*OutboxRelay, error)
NewOutboxRelay creates a relay that polls pending events and publishes them.
func (*OutboxRelay) Start ¶ added in v0.13.0
func (r *OutboxRelay) Start()
Start begins polling in a background goroutine.
func (*OutboxRelay) Stop ¶ added in v0.13.0
func (r *OutboxRelay) Stop()
Stop stops the relay and waits for in-flight publishes.
type PGPool ¶ added in v0.15.0
PGPool is a type alias for pgxpool.Pool, exported so example projects can reference the pool type without importing pgx directly.
type PaginatedResponse ¶
type PaginatedResponse struct {
Data any `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
PaginatedResponse is used by tableCRUD.List (offset mode).
type PoolConf ¶
type PoolConf struct {
// MaxConns is a constant.
MaxConns int32 `json:"max_conns" config:",default=10"`
// MinConns is a constant.
MinConns int32 `json:"min_conns" config:",default=2"`
// MaxConnLifetime is a constant.
MaxConnLifetime string `json:"max_conn_lifetime" config:",optional"`
// MaxConnIdleTime is a constant.
MaxConnIdleTime string `json:"max_conn_idle_time" config:",optional"`
// HealthCheckPeriod is a constant.
HealthCheckPeriod string `json:"health_check_period" config:",optional"`
// ReservedConns is a constant.
ReservedConns int32 `json:"reserved_conns" config:",default=10"`
// StatementTimeout sets statement_timeout per connection.
StatementTimeout string `json:"statement_timeout" config:",optional"`
}
type PoolConfig ¶ added in v0.1.1
type PoolConfig struct {
// MaxIdleConns is a constant.
MaxIdleConns int `json:"max_idle_conns" config:",default=200"`
// MaxIdlePerHost is a constant.
MaxIdlePerHost int `json:"max_idle_conns_per_host" config:",default=100"`
// MaxConnsPerHost is a constant.
MaxConnsPerHost int `json:"max_conns_per_host" config:",default=250"`
// IdleTimeout is a constant.
IdleTimeout string `json:"idle_timeout" config:",default=90s"`
}
type PoolHealth ¶ added in v0.11.0
type PoolHealth struct {
Name string `json:"name"`
Driver string `json:"driver"`
TotalConns int `json:"total_connections"`
IdleConns int `json:"idle_connections"`
InUseConns int `json:"in_use_connections"`
MaxConns int `json:"max_connections"`
UtilizationPct float64 `json:"utilization_pct"`
WaitCount int64 `json:"wait_count"`
WaitDuration string `json:"wait_duration"`
Status string `json:"status"`
}
func CheckPoolHealth ¶ added in v0.11.0
func CheckPoolHealth(name, driver string, pool any) PoolHealth
type PrometheusConfig ¶ added in v0.15.0
type PrometheusConfig struct {
// Enabled enables the prometheus metrics agent and infra/metric counters.
Enabled bool `json:"enabled"`
// Host is the prometheus agent listen address.
Host string `json:"host" config:",default=0.0.0.0"`
// Port is the prometheus agent listen port.
Port int `json:"port" config:",default=9101"`
// Path is the prometheus metrics endpoint path.
Path string `json:"path" config:",default=/metrics"`
}
type RateLimitConf ¶ added in v0.1.0
type RateLimitConf struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",optional"`
// KV is a constant.
KV string `json:"kv" config:",optional"` // references kv[].name
// Algorithm is a constant.
Algorithm string `json:"algorithm" config:",default=sliding_window"`
// TTL is a constant.
TTL string `json:"ttl" config:",optional"`
// Global is a constant.
Global *RateLimitDef `json:"global" config:",optional"`
// PerIP is a constant.
PerIP *RateLimitDef `json:"per_ip" config:",optional"`
// PerUser is a constant.
PerUser *RateLimitDef `json:"per_user" config:",optional"`
// PerKey is a constant.
PerKey *RateLimitDef `json:"per_key" config:",optional"`
// SkipFailedRequests is a constant.
SkipFailedRequests bool `json:"skip_failed_requests" config:",optional"`
// SkipSuccessfulRequests is a constant.
SkipSuccessfulRequests bool `json:"skip_successful_requests" config:",optional"`
}
type RateLimitDef ¶ added in v0.1.0
type Reaper ¶ added in v0.12.0
type Reaper struct {
// contains filtered or unexported fields
}
Reaper periodically calls ReapStale on a JobStore to recover stuck jobs.
type Redirect ¶ added in v0.22.0
type Redirect struct {
// contains filtered or unexported fields
}
Redirect provides a fluent API for HTTP redirects with flash message support. It wraps Fiber's redirect functionality and adds SDK-level conveniences.
Usage:
// Simple redirect
return c.Redirect().To("/login")
// Redirect with status
return c.Redirect().Status(fiber.StatusMovedPermanently).To("/new-path")
// Redirect to named route with params
return c.Redirect().Route("user", runtime.RedirectConfig{
Params: runtime.Map{"id": "123"},
})
// Redirect back to referer (falls back to "/" if missing)
return c.Redirect().Back("/")
// Flash message + redirect
return c.Redirect().With("status", "Logged in").To("/dashboard")
// Flash form input + redirect
return c.Redirect().WithInput().To("/form")
func (*Redirect) Back ¶ added in v0.22.0
Back redirects to the Referer header if it is same-origin, otherwise falls back to the provided fallback URL. If no fallback is given and the referer is missing or cross-origin, it redirects to "/".
Same-origin check normalizes the referer and compares against the request host. Backslashes are folded, ASCII tab/CR/LF are dropped, and leading slash runs are collapsed (matching browser behavior).
func (*Redirect) Message ¶ added in v0.22.0
func (r *Redirect) Message(key string) FlashMessage
Message retrieves a single flash message by key. Returns an empty FlashMessage if the key does not exist.
func (*Redirect) Messages ¶ added in v0.22.0
func (r *Redirect) Messages() []FlashMessage
Messages retrieves all flash messages stored by With() on the previous request.
func (*Redirect) OldInput ¶ added in v0.22.0
func (r *Redirect) OldInput(key string) OldInputData
OldInput retrieves a single old input by key. Returns an empty OldInputData if the key does not exist.
func (*Redirect) OldInputs ¶ added in v0.22.0
func (r *Redirect) OldInputs() []OldInputData
OldInputs retrieves all input data stored by WithInput() on the previous request.
func (*Redirect) Route ¶ added in v0.22.0
func (r *Redirect) Route(name string, config ...RedirectConfig) error
Route redirects to a named route with optional parameters and queries. The route must have been registered with .Name() on the Fiber app.
Example:
app.Get("/user/:id", handler).Name("user")
// ...
return c.Redirect().Route("user", RedirectConfig{
Params: Map{"id": "42"},
Queries: map[string]string{"tab": "profile"},
})
func (*Redirect) Status ¶ added in v0.22.0
Status sets the HTTP status code for the redirect. It is chainable: c.Redirect().Status(301).To("/path")
func (*Redirect) To ¶ added in v0.22.0
To redirects to the given location URL. Default status is 303 See Other unless Status() was called first.
func (*Redirect) With ¶ added in v0.22.0
With stores a flash message that will be available on the next request. Flash messages are stored in a cookie and read via Messages() or Message(key).
Example:
return c.Redirect().With("error", "Invalid credentials").To("/login")
// On next request:
msg := c.Redirect().Message("error") // "Invalid credentials"
func (*Redirect) WithInput ¶ added in v0.22.0
WithInput stores the current request's form/query data as flash input. The data is stored in a cookie and retrievable via OldInputs() or OldInput(key). Captures form, multipart, or query data depending on Content-Type.
Caution: WithInput copies the whole submitted body into a cookie. Sensitive fields (passwords) will be visible. Prefer With() for specific fields.
type RedirectConfig ¶ added in v0.22.0
type RedirectConfig struct {
// Params are the route parameters (e.g. {"id": "123"} for /user/:id).
Params Map
// Queries are query string parameters merged into the redirect URL.
Queries map[string]string
}
RedirectConfig configures a redirect to a named route.
type RedirectDef ¶ added in v0.24.0
type RedirectDef struct {
// From is the source path to match. Supports:
// Exact: "/old"
// Wildcard: "/old/*" (catch-all, forwarded to target)
// Param: "/user/:id" (param forwarded to target)
From string `json:"from"`
// To is the target URL or path. Supports param references:
// "/new" (static target)
// "/new/*" (wildcard forwarded from From)
// "/profile/:id" (param forwarded from From)
// "https://ext.com/x" (external URL)
To string `json:"to"`
// Status is the HTTP status code (default 302).
Status int `json:"status" config:",default=302"`
// Methods limits which HTTP methods trigger the redirect (default: ["GET"]).
Methods []string `json:"methods" config:",optional"`
// PreserveQuery keeps the original query string when redirecting (default: true).
PreserveQuery *bool `json:"preserve_query" config:",optional"`
}
RedirectDef defines a declarative HTTP redirect: from → to with status code. Supports exact paths, wildcard patterns (/old/*), and path param forwarding (:id).
type RedisConfig ¶ added in v0.1.1
type RefreshConfig ¶ added in v0.9.0
type RefreshConfig struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",default=false"`
// TTL is a constant.
TTL int `json:"ttl" config:",default=604800"` // 7 days in seconds
// Endpoint is a constant.
Endpoint string `json:"endpoint" config:",default=/auth/refresh"`
// Secret is a constant.
Secret string `json:"secret" config:",optional"` // separate from auth.secret
// ZitadelTokenURL is a constant.
ZitadelTokenURL string `json:"zitadel_token_url" config:",optional"`
// ZitadelClientID is a constant.
ZitadelClientID string `json:"zitadel_client_id" config:",optional"`
// KratosRefreshURL is a constant.
KratosRefreshURL string `json:"kratos_refresh_url" config:",optional"`
}
type RestCtx ¶ added in v0.4.1
type RestCtx struct {
// contains filtered or unexported fields
}
func (*RestCtx) Redirect ¶ added in v0.6.0
Redirect returns a Redirect object for fluent redirect operations. Supports To(), Status(), Route(), Back(), and flash messages (With/WithInput).
Examples:
return c.Redirect().To("/login")
return c.Redirect().Status(301).To("/new-path")
return c.Redirect().Back("/")
return c.Redirect().With("msg", "saved").To("/list")
func (*RestCtx) ResponseBody ¶ added in v0.4.1
func (*RestCtx) SendStatus ¶ added in v0.4.1
func (*RestCtx) SendString ¶ added in v0.4.1
func (*RestCtx) StatusCode ¶ added in v0.4.1
type RetryConf ¶ added in v0.11.0
type RetryConf struct {
// MaxRetries is the maximum number of retry attempts (default 3).
MaxRetries int `json:"max_retries" config:",default=3"`
// InitialInterval is the initial backoff duration (default 500ms).
InitialInterval string `json:"initial_interval" config:",default=500ms"`
// MaxBackoff is the maximum backoff duration (default 10s).
MaxBackoff string `json:"max_backoff" config:",default=10s"`
// Multiplier is the exponential backoff multiplier (default 2.0).
Multiplier float64 `json:"multiplier" config:",default=2.0"`
}
type SLOConfig ¶ added in v0.14.0
type SLOConfig struct {
// Name identifies this SLO.
Name string
// Target is the availability target (e.g. 99.9 for 99.9%).
Target float64
// Window is the measurement window (e.g. 30d).
Window time.Duration
}
SLOConfig defines a service level objective.
type SSEHandler ¶
SSEHandler is called when an SSE client connects.
type SSRFConf ¶ added in v0.1.0
type SSRFConf struct {
// Enabled is a constant.
Enabled bool `json:"enabled" config:",optional"`
// BlockPrivate is a constant.
BlockPrivate bool `json:"block_private" config:",optional"`
// BlockLoopback is a constant.
BlockLoopback bool `json:"block_loopback" config:",optional"`
// BlockMetadata is a constant.
BlockMetadata bool `json:"block_metadata" config:",optional"`
// AllowedHosts is a constant.
AllowedHosts []string `json:"allowed_hosts" config:",optional"`
}
type SecurityDef ¶ added in v0.2.0
type SecurityDef struct {
// ContentSecurity is a constant.
ContentSecurity *ContentSecurityDef `json:"content_security" config:",optional"`
// Cryption is a constant.
Cryption *CryptionDef `json:"cryption" config:",optional"`
// EncryptCookie is a constant.
EncryptCookie *EncryptCookieDef `json:"encrypt_cookie" config:",optional"`
}
type SecurityHeadersConf ¶ added in v0.1.0
type SecurityHeadersConf struct {
// FrameOptions is a constant.
FrameOptions string `json:"frame_options" config:",optional"`
// ReferrerPolicy is a constant.
ReferrerPolicy string `json:"referrer_policy" config:",optional"`
// PermissionsPolicy is a constant.
PermissionsPolicy string `json:"permissions_policy" config:",optional"`
// HSTS is a constant.
HSTS bool `json:"hsts" config:",optional"`
// HSTSMaxAge is a constant.
HSTSMaxAge int `json:"hsts_max_age" config:",optional"`
// HSTSIncludeSubs is a constant.
HSTSIncludeSubs bool `json:"hsts_include_subdomains" config:",optional"`
// CSP is a constant.
CSP string `json:"csp" config:",optional"`
// CSPConfig is a constant.
CSPConfig *CSPConf `json:"csp_config" config:",optional"` // programmatic CSP builder
// COOP is a constant.
COOP string `json:"coop" config:",optional"`
// COEP is a constant.
COEP string `json:"coep" config:",optional"`
// CORP is a constant.
CORP string `json:"corp" config:",optional"`
// CacheControl is a constant.
CacheControl string `json:"cache_control" config:",optional"`
// CSPReportPath is a constant.
CSPReportPath string `json:"csp_report_path" config:",optional"`
}
type SeedFunc ¶ added in v0.13.0
SeedFunc is a function that runs after databases are initialized but before the HTTP server starts. Use WithSeed to register seeds for DDL creation, data seeding, and other startup tasks that need database access.
type ServerConf ¶
type ServerConf struct {
// Mode sets the server operating mode: "monolith" (default) or "micro".
// In monolith mode, gRPC is disabled and all communication is direct.
// In micro mode, gRPC server and clients are enabled for inter-service calls.
Mode string `json:"mode" config:",default=monolith"`
// Host is a constant.
Host string `json:"host" config:",default=0.0.0.0"`
// Prefork is a constant.
Prefork bool `json:"prefork" config:",optional"`
// BodyLimit is a constant.
BodyLimit int `json:"body_limit" config:",default=4194304"`
// Timeout is a constant.
Timeout string `json:"timeout" config:",default=30s"`
// ReadTimeout is a constant.
ReadTimeout string `json:"read_timeout" config:",default=15s"`
// WriteTimeout is a constant.
WriteTimeout string `json:"write_timeout" config:",default=30s"`
// IdleTimeout is a constant.
IdleTimeout string `json:"idle_timeout" config:",default=120s"`
// Compression is a constant.
Compression bool `json:"compression" config:",optional"`
// StreamRequestBody is a constant.
StreamRequestBody bool `json:"stream_request_body" config:",optional"`
// ReduceMemoryUsage is a constant.
ReduceMemoryUsage bool `json:"reduce_memory_usage" config:",optional"`
// MaxConns is a constant.
MaxConns int `json:"max_conns" config:",default=1000"`
// MaxBytes is a constant.
MaxBytes int `json:"max_bytes" config:",default=4194304"`
// MetricsPath is a constant.
MetricsPath string `json:"metrics_path" config:",default=/metrics"`
// HealthPath is the legacy healthcheck endpoint (always 200 when enabled).
HealthPath string `json:"health_path" config:",default=/healthz"`
// HealthEnabled enables the legacy /healthz endpoint.
HealthEnabled bool `json:"health_enabled" config:",default=true"`
// StartupPath is the startup probe endpoint. It verifies the app has
// successfully started.
StartupPath string `json:"startup_path" config:",default=/startupz"`
// StartupEnabled enables the startup probe endpoint.
StartupEnabled bool `json:"startup_enabled" config:",default=true"`
// ReadinessPath is the readiness probe endpoint. It reports whether the
// server finished starting and its dependencies are reachable.
ReadinessPath string `json:"readiness_path" config:",default=/readyz"`
// ReadinessEnabled enables the readiness probe endpoint.
ReadinessEnabled bool `json:"readiness_enabled" config:",default=true"`
// LivenessPath is the liveness probe endpoint. It reports whether the
// process is running.
LivenessPath string `json:"liveness_path" config:",default=/livez"`
// LivenessEnabled enables the liveness probe endpoint.
LivenessEnabled bool `json:"liveness_enabled" config:",default=true"`
// ShutdownTimeout is a constant.
ShutdownTimeout string `json:"shutdown_timeout" config:",default=10s"`
// RecoverStack is a constant.
RecoverStack bool `json:"recover_stack" config:",default=true"`
// APIPrefix is a constant.
APIPrefix string `json:"api_prefix" config:",default=/api"`
// CORS is a constant.
CORS *CORSConf `json:"cors" config:",optional"`
// CORSGroups is a list of named CORS policies that routes can reference.
CORSGroups []CORSGroupConf `json:"cors_groups" config:",optional"`
// Middleware is a constant.
Middleware []RouteMW `json:"middleware" config:",optional"`
// Static is a constant.
Static []StaticDef `json:"static" config:",optional"`
// Redirects defines declarative HTTP redirects (no Go code needed).
Redirects []RedirectDef `json:"redirects" config:",optional"`
// OpenAPI is a constant.
OpenAPI *OpenAPIConf `json:"openapi" config:",optional"`
// SecurityHeaders is a constant.
SecurityHeaders *SecurityHeadersConf `json:"security_headers" config:",optional"`
// CSPGroups is a list of named per-route CSP policies, like CORSGroups.
CSPGroups []CSPGroupConf `json:"csp_groups" config:",optional"`
// CSRF is a constant.
CSRF *CSRFConf `json:"csrf" config:",optional"`
// RateLimit is a constant.
RateLimit *RateLimitConf `json:"rate_limit" config:",optional"`
// TLS is a constant.
TLS *TLSConf `json:"tls" config:",optional"`
// SSRF is a constant.
SSRF *SSRFConf `json:"ssrf" config:",optional"`
// Cookies is a constant.
Cookies *CookieConf `json:"cookies" config:",optional"`
// Security is a constant.
Security *SecurityDef `json:"security" config:",optional"`
// SlowQueryThreshold is a constant.
SlowQueryThreshold string `json:"slow_query_threshold" config:",default=100ms"`
// GC configures Go runtime garbage collection.
GC *GCConfig `json:"gc" config:",optional"`
// Logger is a constant.
Logger bool `json:"logger" config:",default=true"`
// LoadShedding is a constant.
LoadShedding bool `json:"load_shedding" config:",default=true"`
// Breaker is a constant.
Breaker bool `json:"breaker" config:",default=true"`
// Telemetry is a constant.
Telemetry *TelemetryConf `json:"telemetry" config:",optional"`
// Correlation enables the X-Correlation-ID tracking middleware.
Correlation *CorrelationConf `json:"correlation" config:",optional"`
// LogSkipPaths is a constant.
LogSkipPaths []string `json:"log_skip_paths" config:",optional"`
// LogSampleRate is a constant.
LogSampleRate float64 `json:"log_sample_rate" config:",default=0"`
// GrpcServer configures the gRPC server.
GrpcServer *GrpcServerConf `json:"grpc_server" config:",optional"`
// GrpcClients defines gRPC client connections to other services.
GrpcClients []GrpcClientConf `json:"grpc_clients" config:",optional"`
}
type ServerOverrideDef ¶ added in v0.25.0
type ServerOverrideDef struct {
// URL is the server base URL.
URL string `json:"url"`
// Description documents when this server applies (e.g. "production").
Description string `json:"description" config:",optional"`
}
ServerOverrideDef overrides a server entry in the docs UI.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the main runtime orchestrator. It reads a service YAML, initializes databases, NATS connections, entry endpoints, and optionally exit workers and cron jobs.
func NewFromYAML ¶ added in v0.5.3
NewFromYAML creates a Service from in-memory YAML content (e.g. //go:embed).
func (*Service) AddStatic ¶ added in v0.24.0
func (s *Service) AddStatic(prefix, dir string, opts ...StaticOption) *Service
AddStatic registers a static file route programmatically (alternative to YAML). All parameters are optional with sensible defaults.
Example:
svc.AddStatic("/assets", "./public")
svc.AddStatic("/app", "./dist", runtime.StaticOptSPA(true), runtime.StaticOptCompress(true))
func (*Service) GetGRPCClient ¶ added in v0.12.0
func (s *Service) GetGRPCClient(name string) *GrpcClient
func (*Service) GetGrpcServer ¶ added in v0.12.0
func (s *Service) GetGrpcServer() *GrpcServer
KV returns a KV store (Redis/Dragonfly) connection by name, or nil.
func (*Service) NATS ¶
func (s *Service) NATS(name string) events.EventBroker
NATS returns a event broker connection by name.
func (*Service) PoolPGTyped ¶ added in v0.6.0
PoolPGTyped returns a *pgxpool.Pool by name, or nil if not found.
func (*Service) PoolRead ¶ added in v0.14.0
PoolRead returns a read replica pool if available, falling back to write pool.
func (*Service) RegisterGrpcService ¶ added in v0.15.0
RegisterGrpcService registers a gRPC service factory by proto service name. The factory is called when a "grpc" entry type with matching service_name is declared in the YAML config. Usage:
svc.RegisterGrpcService("AccountService", func(srv *grpc.Server) {
accountpb.RegisterAccountServiceServer(srv, server.NewAccountGRPCServer(pool))
})
func (*Service) RegisterModel ¶
RegisterModel registers a model for OpenAPI schema generation. Usage: svc.RegisterModel("Product", (*Product)(nil)).
func (*Service) RegisterValidation ¶ added in v0.1.0
RegisterValidation registers a validation model by name for input validation. Usage: svc.RegisterValidation("CreateProduct", CreateProductInput{}).
func (*Service) RunWithContext ¶
RunWithContext starts the service with a parent context.
func (*Service) SafeHTTPClient ¶ added in v0.1.0
func (s *Service) SafeHTTPClient() *middleware.SafeHTTPClient
SafeHTTPClient returns an SSRF-protected HTTP client if configured.
func (*Service) SetCORSOriginsFunc ¶ added in v0.19.2
SetCORSOriginsFunc registers a dynamic origin validator for a named CORS group (or the global CORS policy when name is ""). The function is called per preflight request when the origin does not match the YAML allowlist. It must be called before Run.
func (*Service) Storage ¶ added in v0.6.0
func (s *Service) Storage(path string) server.StorageBackend
Storage returns the storage backend registered for a given entry path.
func (*Service) Stream ¶ added in v0.9.0
func (s *Service) Stream(name string) events.EventBroker
Stream returns an event broker connection by name, or nil.
func (*Service) Table ¶ added in v0.1.1
Table returns a *db.Table[T] by model name (registered via MustRegister).
func (*Service) WithAPIKeyValidator ¶ added in v0.8.0
func (s *Service) WithAPIKeyValidator(fn func(ctx context.Context, key string) (*middleware.AuthContext, error)) *Service
WithAPIKeyValidator registers an API key resolver for "manual" auth mode. The resolver receives the raw API key and returns an AuthContext with the key's identity and roles. Return nil to reject the key. Required when api_key: true + driver: manual.
func (*Service) WithAsync ¶ added in v0.1.0
func (s *Service) WithAsync(name string, handler AsyncHandler) *Service
WithAsync registers an async job handler by name.
func (*Service) WithAuthValidator ¶ added in v0.3.0
func (s *Service) WithAuthValidator(fn func(context.Context, *middleware.AuthContext, []string, []string) error) *Service
WithAuthValidator registers a custom authorization validator for "manual" auth mode. The validator receives the AuthContext, YAML-defined roles, and YAML-defined permissions. Return nil if allowed, an error with message if denied.
func (*Service) WithCRUD ¶
func (s *Service) WithCRUD(model string, provider CRUDProvider) *Service
WithCRUD registers a CRUD provider for a model name.
func (*Service) WithCRUDFactory ¶ added in v0.3.1
func (s *Service) WithCRUDFactory(model string, factory CRUDFactory) *Service
WithCRUDFactory registers a lazy CRUD provider factory. The factory is called once on the first HTTP request, after Run() has initialized all resources (database pools, NATS connections, etc.).
func (*Service) WithCron ¶
func (s *Service) WithCron(name string, handler CronJobFunc) *Service
WithCron registers a cron handler by name (for mode=handler).
func (*Service) WithExit ¶
func (s *Service) WithExit(name string, h ExitHandler) *Service
WithExit registers an exit handler by name (for NATS workers).
func (*Service) WithExitHooks ¶
WithExitHooks registers exit hooks by worker name.
func (*Service) WithFS ¶ added in v0.23.0
WithFS registers an fs.FS by name for use in static file definitions. Reference it from YAML with static[].fs: embed and static[].fs_name: <name>.
Example:
//go:embed dist
var distFS embed.FS
svc.WithFS("dist", fs.Sub(distFS, "dist"))
func (*Service) WithHandlers ¶
func (s *Service) WithHandlers(h *EntryHandlers) *Service
WithHandlers registers all entry handler functions.
func (*Service) WithHooks ¶
WithHooks registers entry hooks for a model. The hooks are applied to the corresponding CRUD provider if one has been registered for that model.
func (*Service) WithJWTBlacklist ¶ added in v0.11.0
WithJWTBlacklist registers a callback that checks if a raw JWT is blacklisted. Called after JWT validation succeeds, before the request is processed. Works with all auth drivers: manual, ory, openfga-zitadel. Return true to reject the token (401).
func (*Service) WithOpenAPIMutator ¶ added in v0.25.0
func (s *Service) WithOpenAPIMutator(fn SpecMutator) *Service
WithOpenAPIMutator registers a hook applied to the generated OpenAPI spec before it is served and rendered. Use it for the parts of the docs that the openapi YAML block cannot express (dynamic operations, computed schemas...).
func (*Service) WithRateLimitMaxFunc ¶ added in v0.9.0
WithRateLimitMaxFunc registers a dynamic rate limit resolver. The function receives the SDK RestCtx and returns the max requests per window. Overrides YAML-defined static limits when it returns > 0. Useful for per-tenant, per-user, or per-request dynamic rate limits.
func (*Service) WithSSE ¶
func (s *Service) WithSSE(name string, h SSEHandler) *Service
WithSSE registers an SSE handler by name.
func (*Service) WithScalarOptions ¶ added in v0.25.0
WithScalarOptions appends raw scalar-go render options on top of everything configured via the openapi YAML block. Escape hatch for exotic needs.
func (*Service) WithSeed ¶ added in v0.13.0
WithSeed registers a seed function that runs after database initialization but before the HTTP server starts. Seeds receive the Service with all pools already initialized. Use for DDL, data seeding, and startup validation.
Example:
svc.WithSeed(func(ctx context.Context, s *runtime.Service) error {
pool := s.PoolPGTyped("primary")
_, err := pool.Exec(ctx, "CREATE TABLE IF NOT EXISTS ...")
return err
})
type ServiceConfig ¶
type ServiceConfig struct {
// Name is a constant.
Name string `json:"name"`
// Port is a constant.
Port int `json:"port" config:",default=8080"`
// Deploy is a constant.
Deploy *DeployConfig `json:"deploy" config:",optional"`
// Server is a constant.
Server ServerConf `json:"server" config:",optional"`
// Databases is a constant.
Databases []DBConfig `json:"databases" config:",optional"`
// KV is a constant.
KV []KVConfig `json:"kv" config:",optional"`
// Stream is a constant.
Stream []StreamConfig `json:"stream" config:",optional"`
// Entry is a constant.
Entry []EntryDef `json:"entry" config:",optional"`
// Exit is a constant.
Exit []ExitWorker `json:"exit" config:",optional"`
// Cron is a constant.
Cron []CronJob `json:"cron" config:",optional"`
// Auth is a constant.
Auth *AuthConfig `json:"auth" config:",optional"`
// Log is a constant.
Log *logx.LogConf `json:"log" config:",optional"`
// Prometheus enables prometheus metrics via infra/metric.
Prometheus *PrometheusConfig `json:"prometheus" config:",optional"`
}
func LoadConfig ¶
func LoadConfig(path string) (*ServiceConfig, error)
func ParseConfig ¶ added in v0.5.3
func ParseConfig(content []byte) (*ServiceConfig, error)
type SlowQueryConf ¶ added in v0.11.0
type SourceDef ¶ added in v0.25.0
type SourceDef struct {
// Title shown on the docs tab.
Title string `json:"title"`
// Slug is the URL fragment used to route to this document.
Slug string `json:"slug" config:",optional"`
// URL points at an OpenAPI spec (e.g. http://ms-email:3107/openapi.json).
URL string `json:"url" config:",optional"`
// Default marks the tab displayed first.
Default bool `json:"default" config:",optional"`
}
SourceDef declares an additional OpenAPI document rendered as a docs tab.
type SpecMutator ¶ added in v0.25.0
registerDocs registers /openapi.json and /docs (Scalar UI) endpoints if the server.openapi.enabled config is true. SpecMutator mutates the generated OpenAPI spec before it is marshaled and rendered. Use it for spec content that YAML cannot express.
type SpoolDef ¶ added in v0.17.0
type SpoolDef struct {
// Mode is a constant.
Mode string `json:"mode" config:",default=auto,options=auto|memory|disk"`
// MemoryLimit is a constant.
MemoryLimit string `json:"memory_limit" config:",default=4MB"`
// Dir is a constant.
Dir string `json:"dir" config:",optional"`
// PartSize is a constant.
PartSize string `json:"multipart_part_size" config:",default=16MB"`
// Concurrency is a constant.
Concurrency int `json:"multipart_concurrency" config:",default=4"`
// Async is a constant.
Async bool `json:"async" config:",optional"`
}
SpoolDef configures streaming uploads: the request body is ingested to memory (up to MemoryLimit) and then to local disk before uploading to S3 with multipart. Async returns 202 and uploads in background.
type StaticDef ¶
type StaticDef struct {
// Prefix is the URL prefix for serving files (e.g. "/assets").
Prefix string `json:"prefix"`
// Dir is the directory path on disk (e.g. "./public").
// Required when FS is not set.
Dir string `json:"dir" config:",optional"`
// FS selects the filesystem source: "" or "disk" uses Dir on disk;
// "embed" uses an fs.FS registered via WithFS(name).
FS string `json:"fs" config:",optional"`
// FSName references the fs.FS registered via Service.WithFS(name, fsys).
// Required when fs: "embed".
FSName string `json:"fs_name" config:",optional"`
// Compress enables gzip/brotli/zstd compression for served files.
Compress bool `json:"compress" config:",optional"`
// ByteRange enables byte range requests (useful for video/audio).
ByteRange bool `json:"byte_range" config:",optional"`
// Browse enables directory listing when a directory is requested.
Browse bool `json:"browse" config:",optional"`
// Download sets Content-Disposition: attachment for direct downloads.
Download bool `json:"download" config:",optional"`
// MaxAge sets Cache-Control max-age in seconds. 0 means no cache header.
MaxAge int `json:"max_age" config:",default=0"`
// IndexNames overrides the default index file names (default: ["index.html"]).
IndexNames []string `json:"index_names" config:",optional"`
// SPA enables Single-Page Application mode: when a file is not found,
// the handler serves the first index file instead of returning 404.
SPA bool `json:"spa" config:",optional"`
// Methods limits which HTTP methods serve files (default: ["GET", "HEAD"]).
Methods []string `json:"methods" config:",optional"`
}
type StaticOption ¶ added in v0.24.0
type StaticOption func(*StaticDef)
StaticOption configures AddStatic.
func StaticOptBrowse ¶ added in v0.24.0
func StaticOptBrowse(v bool) StaticOption
StaticOptBrowse enables directory listing.
func StaticOptByteRange ¶ added in v0.24.0
func StaticOptByteRange(v bool) StaticOption
StaticOptByteRange enables byte range requests.
func StaticOptCompress ¶ added in v0.24.0
func StaticOptCompress(v bool) StaticOption
StaticOptCompress enables gzip/brotli/zstd compression.
func StaticOptDownload ¶ added in v0.24.0
func StaticOptDownload(v bool) StaticOption
StaticOptDownload sets Content-Disposition: attachment.
func StaticOptIndexNames ¶ added in v0.24.0
func StaticOptIndexNames(v ...string) StaticOption
StaticOptIndexNames sets custom index file names.
func StaticOptMaxAge ¶ added in v0.24.0
func StaticOptMaxAge(v int) StaticOption
StaticOptMaxAge sets Cache-Control max-age in seconds.
func StaticOptMethods ¶ added in v0.24.0
func StaticOptMethods(v ...string) StaticOption
StaticOptMethods sets which HTTP methods serve files.
func StaticOptSPA ¶ added in v0.24.0
func StaticOptSPA(v bool) StaticOption
StaticOptSPA enables SPA fallback mode.
type StorageDef ¶
type StorageDef struct {
// Mode is a constant.
Mode string `json:"mode"` // s3, local
// Bucket is a constant.
Bucket string `json:"bucket" config:",optional"`
// Path is a constant.
Path string `json:"path" config:",optional"`
// Region is a constant.
Region string `json:"region" config:",optional"`
// Endpoint is a constant.
Endpoint string `json:"endpoint" config:",optional"`
// AccessKey is a constant.
AccessKey string `json:"access_key" config:",optional"`
// SecretKey is a constant.
SecretKey string `json:"secret_key" config:",optional"`
// Presign is a constant.
Presign bool `json:"presign" config:",optional"`
// PresignTTL is a constant.
PresignTTL string `json:"presign_ttl" config:",default=5m"`
// Pool is a constant.
Pool *PoolConfig `json:"pool" config:",optional"`
// Spool is a constant.
Spool *SpoolDef `json:"spool" config:",optional"`
// Cache is a constant.
Cache *CacheConfig `json:"cache" config:",optional"`
}
type StreamConfig ¶ added in v0.9.0
type StreamConfig struct {
// Name is a constant.
Name string `json:"name"`
// Driver is a constant.
Driver string `json:"driver" config:",default=nats"`
// URL is a constant.
URL string `json:"url" config:",optional"`
// Brokers is a constant.
Brokers []string `json:"brokers" config:",optional"`
// ConsumerGroup is a constant.
ConsumerGroup string `json:"consumer_group" config:",optional"`
// MaxReconnects is a constant.
MaxReconnects int `json:"max_reconnects" config:",optional"`
// ReconnectWait is a constant.
ReconnectWait string `json:"reconnect_wait" config:",optional"`
// Timeout is a constant.
Timeout string `json:"timeout" config:",optional"`
// RetryOnFail is a constant.
RetryOnFail bool `json:"retry_on_fail" config:",optional"`
// User authenticates to the NATS server. Password may be set directly or
// referenced from the environment with ${VAR} (the config expands it).
User string `json:"user" config:",optional"`
// Password authenticates to the NATS server.
Password string `json:"password" config:",optional"`
// CAFile verifies the server certificate (leave empty for system roots).
CAFile string `json:"ca_file" config:",optional"`
// CertFile/KeyFile are the client certificate pair for mTLS servers.
CertFile string `json:"cert_file" config:",optional"`
KeyFile string `json:"key_file" config:",optional"`
// Streams is a constant.
Streams []StreamDef `json:"streams" config:",optional"`
}
type StreamDef ¶
type StreamDef struct {
// Name is a constant.
Name string `json:"name"`
// MaxAge is a constant.
MaxAge string `json:"max_age" config:",optional"`
// MaxBytes is a constant.
MaxBytes int64 `json:"max_bytes" config:",optional"`
// Storage is a constant.
Storage string `json:"storage" config:",default=file"`
// Compression is a constant.
Compression string `json:"compression" config:",default=s2"`
}
type SubscribeDef ¶
type TLSConf ¶ added in v0.1.0
type TLSConf struct {
// Enabled is a constant.
Enabled bool `json:"enabled"`
// Manual is a constant.
Manual *ManualTLS `json:"manual" config:",optional"`
// Autocert is a constant.
Autocert *AutocertTLS `json:"autocert" config:",optional"`
// MinVersion is a constant.
MinVersion string `json:"min_version" config:",optional"`
// MaxVersion is a constant.
MaxVersion string `json:"max_version" config:",optional"`
// CurvePrefs is a constant.
CurvePrefs []string `json:"curve_preferences" config:",optional"`
// CipherSuites is a constant.
CipherSuites []string `json:"cipher_suites" config:",optional"`
// RedirectHTTP is a constant.
RedirectHTTP bool `json:"redirect_http" config:",optional"`
// RedirectPort is a constant.
RedirectPort int `json:"redirect_port" config:",optional"`
}
type TelemetryConf ¶ added in v0.1.1
type TelemetryConf struct {
Enabled bool `json:"enabled" config:",optional"`
Name string `json:"name" config:",optional"`
// Endpoint is the OTLP receiver address (e.g. "localhost:4317").
Endpoint string `json:"endpoint" config:",optional"`
Sampler float64 `json:"sampler" config:",default=1.0"`
// Batcher is the exporter type: otlpgrpc | otlphttp | zipkin | file.
Batcher string `json:"batcher" config:",default=otlpgrpc"`
// OtlpHeaders are additional headers sent with OTLP export requests.
OtlpHeaders map[string]string `json:"otlp_headers" config:",optional"`
// OtlpHttpPath is the URL path for OTLP HTTP transport (e.g. "/v1/traces").
OtlpHttpPath string `json:"otlp_http_path" config:",optional"`
// OtlpHttpSecure enables TLS for OTLP HTTP transport.
OtlpHttpSecure bool `json:"otlp_http_secure" config:",optional"`
// TraceResponseHeader sets a response header exposing the trace ID (e.g. "X-Trace-Id").
TraceResponseHeader string `json:"trace_response_header" config:",optional"`
// SkipPaths are request paths that should not be traced.
SkipPaths []string `json:"skip_paths" config:",optional"`
}
Source Files
¶
- async_job.go
- async_store.go
- async_store_factory.go
- async_store_nats.go
- async_store_pg.go
- async_store_redis.go
- bulkhead.go
- config.go
- cron.go
- db_health.go
- db_metrics.go
- db_resolver.go
- docs.go
- entry.go
- entry_async.go
- entry_crud.go
- entry_file.go
- entry_graphql.go
- entry_grpc.go
- entry_realtime.go
- entry_rest.go
- exit.go
- graphql_resolver.go
- graphql_schema.go
- grpc.go
- grpc_interceptors.go
- grpc_proto.go
- grpc_resolver.go
- hooks.go
- lazy_crud.go
- openapi.go
- outbox.go
- redirect.go
- redis.go
- rest_ctx.go
- service.go
- slo.go
- table_provider.go
- util.go
- validate.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth provides password hashing, verification, token generation, and role hierarchy utilities.
|
Package auth provides password hashing, verification, token generation, and role hierarchy utilities. |