Documentation
¶
Index ¶
- Constants
- Variables
- func Configure(envPrefix string, cfgs ...Configurable) error
- func ContextWithCorrelationID(ctx context.Context, id string) context.Context
- func CorrelationIDFromContext(ctx context.Context) string
- func IsBadRequestError(err error) bool
- func IsBusinessError(err error) bool
- func IsForbiddenError(err error) bool
- func IsInternalError(err error) bool
- func IsNotFoundError(err error) bool
- func IsUnauthorizedError(err error) bool
- func NewLogger(config *LogConfig, forceDebug bool) *slog.Logger
- func SortableMSToTime(st string) time.Time
- func SortableToTime(st string) time.Time
- func TimeToSortable(t time.Time) string
- func TimeToSortableMS(t time.Time) string
- func TruncateToSecond(t time.Time) time.Time
- type Clock
- type Closer
- type ConfigReader
- type Configurable
- type Error
- func GetError(err error) *Error
- func NewBadRequestError(subject, message string) *Error
- func NewBusinessError(subject, message string) *Error
- func NewError(errorType ErrorType, subject, message string) *Error
- func NewForbiddenError(subject, message string) *Error
- func NewInternalError(subject, message string) *Error
- func NewNotFoundError(subject, message string) *Error
- func NewUnauthorizedError(subject, message string) *Error
- func (e *Error) Error() string
- func (e *Error) Is(target error) bool
- func (e *Error) MarshalJSON() ([]byte, error)
- func (e *Error) Unwrap() error
- func (e *Error) WithCode(code int) *Error
- func (e *Error) WithInner(inner error) *Error
- func (e *Error) WithMessage(message string, params ...any) *Error
- func (e *Error) WithParams(keyvals ...any) *Error
- func (e *Error) WithSubject(subject string) *Error
- type ErrorResponse
- type ErrorType
- type FixedClock
- type HealthChecker
- type Initer
- type LogConfig
- type LogOutputConfig
- type NowProvider
- type Setupper
- type Starter
- type TimeProvider
Constants ¶
const CorrelationIDHeader = "X-Request-ID"
CorrelationIDHeader is the canonical header carrying a correlation (request) id across process boundaries — HTTP requests and message broker frames alike. httpx and messaging both read and write this header so an id flows uniformly http -> messaging -> http.
Variables ¶
var ( ErrBadRequest = NewBadRequestError("General", "Bad Request") ErrNotFound = NewNotFoundError("General", "Not Found") ErrBusiness = NewBusinessError("General", "Business") ErrForbidden = NewForbiddenError("General", "Forbidden") ErrInternal = NewInternalError("General", "Internal") )
Functions ¶
func Configure ¶ added in v0.4.0
func Configure(envPrefix string, cfgs ...Configurable) error
Configure creates a single ConfigReader and calls ReadConfig on each Configurable in order. Use NewConfigReader when you need to reuse the same parsed config across multiple calls.
func ContextWithCorrelationID ¶ added in v0.7.0
ContextWithCorrelationID returns a copy of ctx carrying the correlation id. It is the single source of truth for the correlation-id context key, shared by every microjet layer so the id survives across http and messaging hops.
func CorrelationIDFromContext ¶ added in v0.7.0
CorrelationIDFromContext returns the correlation id stored in ctx, or "" if none is present.
func IsBadRequestError ¶
func IsBusinessError ¶
func IsForbiddenError ¶
func IsInternalError ¶
func IsNotFoundError ¶
func IsUnauthorizedError ¶
func NewLogger ¶
NewLogger constructs a *slog.Logger from LogConfig. Console output is always enabled unless config.Console.Enabled=false. A second file output is added when config.File.Enabled=true and config.File.Path is set. Each output has its own level and format, falling back to config.Level and config.Format.
func SortableMSToTime ¶
func SortableToTime ¶
func TimeToSortable ¶
func TimeToSortableMS ¶
TimeToSortableMS formats t as a 17-digit lexicographically sortable string with millisecond precision: YYYYMMDDHHMMSSmmm. Go only recognizes fractional seconds when preceded by a separator, so we format with a dot and strip it.
Types ¶
type Clock ¶
type Clock struct {
// contains filtered or unexported fields
}
func NewClock ¶ added in v0.11.0
func NewClock(now NowProvider) *Clock
func (*Clock) NowSortable ¶ added in v0.11.0
func (*Clock) NowSortableMS ¶ added in v0.11.0
type Closer ¶ added in v0.4.0
type Closer interface {
Close() error
}
Closer is implemented by services that need to release resources on shutdown. The host calls Close on each registered service that implements this interface (host.ServiceCloser takes precedence when present).
type ConfigReader ¶ added in v0.11.0
type ConfigReader interface {
SetDefault(key string, value any)
Read(key string, dest any) error
ReadMap(key string) map[string]any
ReadAll(dest any) error
}
ConfigReader wraps a reader instance and exposes config-reading operations to Configurable implementations.
func NewViperConfigReader ¶ added in v0.11.0
func NewViperConfigReader(envPrefix string) (ConfigReader, error)
NewViperConfigReader creates a ConfigReader. Use this to hold a single reader across multiple Configure calls (e.g. in App.configReader) so the config file is only read once.
type Configurable ¶ added in v0.4.0
type Configurable interface {
ReadConfig(ConfigReader) error
}
Configurable is implemented by any type that can populate itself from a ConfigReader. ReadConfig is called on each registered value in order.
type Error ¶
type Error struct {
Type ErrorType `json:"type"`
Subject string `json:"subject"`
Message string `json:"message"`
Params map[string]any `json:"params,omitempty"`
Code int `json:"code"`
Inner error `json:"-"`
}
func NewBadRequestError ¶
func NewBusinessError ¶
func NewForbiddenError ¶
func NewInternalError ¶
func NewNotFoundError ¶
func NewUnauthorizedError ¶
func (*Error) Is ¶
Is reports whether e matches target for errors.Is, letting a typed *Error be used as a sentinel by category. target matches when it is an *Error of the same Type; if target also sets a non-zero Code it must match, and if target sets a Subject other than the default "General" it must match too. This makes the package sentinels match any error of their category — errors.Is(err, ErrNotFound) is true for any NotFound error — while a custom sentinel carrying a Subject and/or Code matches more narrowly. Wrapped non-Error sentinels still match through Unwrap as usual.
func (*Error) MarshalJSON ¶
func (*Error) WithMessage ¶
WithMessage returns a copy of the error with the message replaced. Optional key-value pairs are merged into Params (same semantics as WithParams).
func (*Error) WithParams ¶
WithParams returns a copy of the error with additional key-value pairs merged into Params. Keys must be strings; non-string keys are silently skipped.
func (*Error) WithSubject ¶
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error"`
Subject string `json:"subject"`
Message string `json:"message"`
Params map[string]any `json:"params,omitempty"`
Code int `json:"code"`
InnerError *string `json:"innerError,omitempty"`
}
ErrorResponse is the JSON body returned by the HTTP error middleware.
type ErrorType ¶
type ErrorType string
ErrorType identifies the category of an error and controls HTTP status mapping: BadRequest→400, Unauthorized→401, Forbidden→403, NotFound→404, Business→409, Internal→500.
func GetErrorType ¶
type FixedClock ¶
FixedClock is a TimeProvider that reports a preset time, for deterministic tests. It is not safe for concurrent mutation; set the time before use.
func NewFixedClock ¶
func NewFixedClock(t time.Time) *FixedClock
func (*FixedClock) Advance ¶
func (c *FixedClock) Advance(d time.Duration)
Advance moves the clock forward by d.
func (*FixedClock) Set ¶
func (c *FixedClock) Set(t time.Time)
Set replaces the time the clock reports.
type HealthChecker ¶ added in v0.4.0
HealthChecker is implemented by services that can report whether they are ready to serve traffic. The host's /readyz probe consults every registered service implementing it, so databases, cache, messaging, and any user service that implements this interface are covered without per-type wiring. Healthy returns nil when ready and a self-describing error otherwise.
type Initer ¶ added in v0.4.0
type Initer interface {
Init() error
}
Initer is implemented by services that need to perform initialization after their config is loaded but do not require host-level DI. The host calls Init on each registered service that implements this interface (host.ServiceIniter, which carries *App, takes precedence).
type LogConfig ¶
type LogConfig struct {
Level string `mapstructure:"level"`
Format string `mapstructure:"format"`
Console *LogOutputConfig `mapstructure:"console"`
File *LogOutputConfig `mapstructure:"file"`
}
LogConfig configures the logger. Console output is always enabled unless explicitly disabled via Console.Enabled=false. A file output is added when File.Enabled=true and File.Path is set. Each output can independently override the top-level Level and Format. Valid levels: debug, info, warn, error. Valid formats: text, json.
type LogOutputConfig ¶
type LogOutputConfig struct {
Enabled bool `mapstructure:"enabled"`
Level string `mapstructure:"level"` // overrides LogConfig.Level for this output
Format string `mapstructure:"format"` // overrides LogConfig.Format for this output
Path string `mapstructure:"path"` // file output only; parent dirs are created automatically
}
LogOutputConfig configures a single log output destination (console or file).
type NowProvider ¶ added in v0.11.0
type Setupper ¶ added in v0.14.0
type Setupper interface {
Setup() error
}
Setupper is implemented by services that need to perform post-init work once every service has finished Init — typically work that depends on other services being connected (running migrations, finalizing route registration). It runs in the same phase as host.App.Setup handlers but is co-located on the service itself. The host calls Setup on each registered service implementing this interface (host.ServiceSetupper, which carries *App, takes precedence).
type Starter ¶ added in v0.4.0
type Starter interface {
Start() error
}
Starter is implemented by services that begin active work (serving, listening) only after every service has finished Init. Splitting Start from Init gives the host a window between "resources acquired" and "serving" in which setup work (migrations, route registration) can run. The host calls Start on each registered service implementing this interface (host.ServiceStarter, which carries *App, takes precedence).
type TimeProvider ¶
type TimeProvider interface {
Now() time.Time
NowTS() int64
NowSortable() string
NowSortableMS() string
}
TimeProvider supplies the current time. Inject it (e.g. via host.WithClock) so time-dependent code can be made deterministic in tests by swapping in a FixedClock instead of reaching for time.Now() directly.