core

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
var (
	ErrBadRequest   = NewBadRequestError("General", "Bad Request")
	ErrNotFound     = NewNotFoundError("General", "Not Found")
	ErrBusiness     = NewBusinessError("General", "Business")
	ErrUnauthorized = NewUnauthorizedError("General", "Unauthorized")
	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

func ContextWithCorrelationID(ctx context.Context, id string) context.Context

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

func CorrelationIDFromContext(ctx context.Context) string

CorrelationIDFromContext returns the correlation id stored in ctx, or "" if none is present.

func IsBadRequestError

func IsBadRequestError(err error) bool

func IsBusinessError

func IsBusinessError(err error) bool

func IsForbiddenError

func IsForbiddenError(err error) bool

func IsInternalError

func IsInternalError(err error) bool

func IsNotFoundError

func IsNotFoundError(err error) bool

func IsUnauthorizedError

func IsUnauthorizedError(err error) bool

func NewLogger

func NewLogger(config *LogConfig, forceDebug bool) *slog.Logger

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 SortableMSToTime(st string) time.Time

func SortableToTime

func SortableToTime(st string) time.Time

func TimeToSortable

func TimeToSortable(t time.Time) string

func TimeToSortableMS

func TimeToSortableMS(t time.Time) string

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.

func TruncateToSecond

func TruncateToSecond(t time.Time) time.Time

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) Now added in v0.11.0

func (c *Clock) Now() time.Time

func (*Clock) NowSortable added in v0.11.0

func (c *Clock) NowSortable() string

func (*Clock) NowSortableMS added in v0.11.0

func (c *Clock) NowSortableMS() string

func (*Clock) NowTS added in v0.11.0

func (c *Clock) NowTS() int64

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 GetError

func GetError(err error) *Error

func NewBadRequestError

func NewBadRequestError(subject, message string) *Error

func NewBusinessError

func NewBusinessError(subject, message string) *Error

func NewError

func NewError(errorType ErrorType, subject, message string) *Error

func NewForbiddenError

func NewForbiddenError(subject, message string) *Error

func NewInternalError

func NewInternalError(subject, message string) *Error

func NewNotFoundError

func NewNotFoundError(subject, message string) *Error

func NewUnauthorizedError

func NewUnauthorizedError(subject, message string) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

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 (e *Error) MarshalJSON() ([]byte, error)

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) WithCode

func (e *Error) WithCode(code int) *Error

func (*Error) WithInner

func (e *Error) WithInner(inner error) *Error

func (*Error) WithMessage

func (e *Error) WithMessage(message string, params ...any) *Error

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

func (e *Error) WithParams(keyvals ...any) *Error

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

func (e *Error) WithSubject(subject string) *Error

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.

const (
	BadRequestErrorType   ErrorType = "BAD_REQUEST"
	NotFoundErrorType     ErrorType = "NOT_FOUND"
	BusinessErrorType     ErrorType = "BUSINESS"
	UnauthorizedErrorType ErrorType = "UNAUTHORIZED"
	ForbiddenErrorType    ErrorType = "FORBIDDEN"
	InternalErrorType     ErrorType = "INTERNAL"
)

func GetErrorType

func GetErrorType(err error) (ErrorType, bool)

type FixedClock

type FixedClock struct {
	*Clock
	Time time.Time
}

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

type HealthChecker interface {
	Healthy(ctx context.Context) error
}

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 NowProvider func() time.Time

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.

var (
	UTC   TimeProvider = NewClock(func() time.Time { return time.Now().UTC() })
	Local TimeProvider = NewClock(func() time.Time { return time.Now() })
)

UTC is the default real-time clock, used when no clock is injected.

Jump to

Keyboard shortcuts

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