corefx

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 21 Imported by: 0

README

Core FX

Integrate core feature like configuration slog and sentry into FX.

Requires go 1.24+

Install

go get -u github.com/mawngo/go-corefx

Usage

By default, core fx module will load configuration from .configs/app.json then enviroment variables

package main

import (
	"encoding/json"
	"github.com/mawngo/go-corefx"
	"go.uber.org/fx"
)

func main() {
	fx.New(
		configModule,
		corefx.NewModule(),
		fx.Invoke(func(c *myConfig, s fx.Shutdowner) {
			b, _ := json.Marshal(c)
			// app.json: {"app_version": "1.1.1", "log_level": "warn"}
			println(string(b)) // {"app_name":"example","app_version":"1.1.1","log_level":"warn","profile":"","sentry_dsn":"","sentry_log_level":""}
			_ = s.Shutdown()
		}),
	).Run()
}

// requiredConfigModule create a required module that provide corefx.CoreConfig.
var configModule = fx.Module("config",
	fx.Provide(
		newConfig,
		corefx.As[*myConfig](
			new(corefx.CoreConfig),
			new(corefx.SentryConfig), // Optional.
		),
	),
)

// myConfig Create a custom required struct that implement corefx.CoreConfig.
type myConfig struct {
	corefx.CoreEnv
}

func newConfig() *myConfig {
	return &myConfig{
		CoreEnv: corefx.CoreEnv{
			AppName:  "example",
			LogLevel: "info",
		},
	}
}

func (c *myConfig) ProfileValue() string {
	return c.Profile
}

Required: all config implementer should support UnmarshalJSON and MarshalJSON.

Documentation

Index

Constants

View Source
const (
	ConfigFolder = "configs"
	ConfigFile   = "app.json"
)
View Source
const (
	ProfileProduction  = "production"
	ProfileDevelopment = "development"
	ProfileDebug       = "debug"
)
View Source
const (
	HealthStatusUp    = "UP"
	HealthStatusDown  = "DOWN"
	HealthUnavailable = "UNAVAILABLE"
)

Variables

View Source
var ErrUnavailable = errors.New("err unavailable")

ErrUnavailable indicate that the service is busy/overload, thus not able to process new traffic. For other cases like connection failure, deadlock, ... the service should return more specific error instead.

Functions

func As added in v1.1.0

func As[T any](types ...any) any

As register already registered type T under multiple interfaces. Useful if you need a single required object to provide multiple required types. This method allows you to inject the original object, and all type it registered by this function.

func AsIndicator added in v1.4.0

func AsIndicator(f any) any

AsIndicator register function into HealthIndicator.

func From added in v1.1.0

func From[T any]() any

From create a function that accepts and return self. This method can be used with other As... methods of multiple fx packages when you want to keep both the original type and annotated type after annotated. For example, fx.Provide(newMyService, AsInterface(From[*myService])).

func LoadJSONConfig

func LoadJSONConfig(p LoadJSONConfigParams) error

LoadJSONConfig load config into CoreConfig.

func LoadJSONConfigInto

func LoadJSONConfigInto(cfg any, automaticEnv bool, defaultCfgPath string) error

LoadJSONConfigInto load json config into cfg pointer.

func NewCoreModule added in v1.4.0

func NewCoreModule() fx.Option

NewCoreModule Create a module that autoconfigure slog, sentry and populate configuration from file or environment. The env config object must implement CoreConfig, and registered using AsConfigFor to be autopopulated. The env config must also register as SentryConfig to enable sentry feature.

func NewGlobalSlogLogger

func NewGlobalSlogLogger(p SlogLoggerParams) (*slog.Logger, error)

NewGlobalSlogLogger create a logger instance and register it globally.

func NewModule

func NewModule() fx.Option

NewModule register core module and enable health check support.

func UseSlogLogger

func UseSlogLogger() fx.Option

UseSlogLogger configure fx to use slog.Default logger.

Types

type AvailabilityProbeParams added in v1.4.0

type AvailabilityProbeParams struct {
	fx.In
	Checkers []HealthIndicator `group:"health_indicator"`
}

type CoreConfig

type CoreConfig interface {
	// AppNameValue application name.
	AppNameValue() string
	// AppVersionValue application version.
	AppVersionValue() string
	// AppConfigLocationValue base config file to load from.
	// Config file must in JSON format.
	// Return empty string to disable loading from a config file.
	// Default implementations read config from file:./configs/app.json.
	AppConfigLocationValue() (string, error)
	// AppAutomaticEnvValue enable read env variable into config struct automatically.
	AppAutomaticEnvValue() bool
	// ProfileValue application env profile (production,development,debug).
	ProfileValue() string
	// RequiredValues the list of field that must specify.
	// This method must return a list of pointers to specified field on the same object.
	RequiredValues() []any
	// LogLevelValue application log level.
	LogLevelValue() string
	// LogFormatValue the format of log, accept "text", "json"
	LogFormatValue() string
	// IsProd shorthand production profile checking.
	IsProd() bool
}

type CoreEnv

type CoreEnv struct {
	AppName    string `json:"app_name" mapstructure:"app_name"`
	AppVersion string `json:"app_version" mapstructure:"app_version"`
	LogLevel   string `json:"log_level" mapstructure:"log_level"`
	Profile    string `json:"profile" mapstructure:"profile"`
	SentryEnv
}

nolint:staticcheck

func NewEnv

func NewEnv() CoreEnv

func (CoreEnv) AppAutomaticEnvValue

func (e CoreEnv) AppAutomaticEnvValue() bool

func (CoreEnv) AppConfigLocationValue

func (e CoreEnv) AppConfigLocationValue() (string, error)

func (CoreEnv) AppNameValue

func (e CoreEnv) AppNameValue() string

func (CoreEnv) AppVersionValue

func (e CoreEnv) AppVersionValue() string

func (CoreEnv) IsProd

func (e CoreEnv) IsProd() bool

func (CoreEnv) LogFormatValue added in v1.1.0

func (e CoreEnv) LogFormatValue() string

func (CoreEnv) LogLevelValue

func (e CoreEnv) LogLevelValue() string

func (CoreEnv) ProfileValue

func (e CoreEnv) ProfileValue() string

func (CoreEnv) RequiredValues

func (e CoreEnv) RequiredValues() []any

type Health added in v1.4.0

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

Health report the combined readiness/liveness of all HealthIndicator.

func NewHealth added in v1.4.0

func NewHealth(p AvailabilityProbeParams) *Health

NewHealth create new Health instance.

func (*Health) Liveness added in v1.4.0

func (p *Health) Liveness(ctx context.Context) (bool, map[HealthIndicator]HealthStatus)

func (*Health) Readiness added in v1.4.0

func (p *Health) Readiness(ctx context.Context) (bool, map[HealthIndicator]HealthStatus)

type HealthIndicator added in v1.4.0

type HealthIndicator interface {
	Readiness(ctx context.Context) error
	Liveness(ctx context.Context) error
}

HealthIndicator an empty interface for registering type for health probing.

type HealthStatus added in v1.4.0

type HealthStatus struct {
	Status string `json:"status"`
	Err    error  `json:"-"`
}

type LoadJSONConfigParams

type LoadJSONConfigParams struct {
	fx.In
	Config CoreConfig
}

type Named added in v1.3.0

type Named interface {
	Name() string
}

Named indicate that this service has a name (which may not unique between services).

type ReadinessThresholder added in v1.4.0

type ReadinessThresholder interface {
	ReadinessThreshold() int
}

ReadinessThresholder configure maximum number of continuously not-ready probes before this instance considered failure. By default, this value is -1, meaning that the readiness status should not affect liveness status.

type SentryConfig

type SentryConfig interface {
	SentryDsnValue() string
	SentryLogLevelValue() string
}

type SentryEnv

type SentryEnv struct {
	SentryDsn      string `json:"sentry_dsn" mapstructure:"sentry_dsn"`
	SentryLogLevel string `json:"sentry_log_level" mapstructure:"sentry_log_level"`
}

func (SentryEnv) SentryDsnValue

func (e SentryEnv) SentryDsnValue() string

func (SentryEnv) SentryLogLevelValue

func (e SentryEnv) SentryLogLevelValue() string

type SlogLoggerParams

type SlogLoggerParams struct {
	fx.In
	Config    CoreConfig
	LogConfig SentryConfig `optional:"true"`
	Lifecycle fx.Lifecycle
}

Directories

Path Synopsis
examples
config command
required command

Jump to

Keyboard shortcuts

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