gone

package module
v2.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2025 License: MIT Imports: 17 Imported by: 55

README

English  |  中文

license GoDoc Go Report Card codecov Build and Test Release Mentioned in Awesome Go

logo

Gone

Gone 是基于Golang标签的依赖注入框架

Gone 是一个轻量级的golang依赖注入框架,下面是一个简单的例子(嵌入了gone.Flag的结构体,我们称之为Goner):

package main

import "github.com/gone-io/gone/v2"

type Dep struct {
	gone.Flag
	Name string
}

type Component struct {
	gone.Flag
	dep *Dep        `gone:"*"` //依赖注入
	log gone.Logger `gone:"*"`
}

func (c *Component) Init() {
	c.log.Infof(c.dep.Name) //使用依赖
}

func main() {
	gone.
		NewApp().
		// 组件注册加载
		Load(&Dep{Name: "Component Dep"}).
		Load(&Component{}).
		//运行
		Run()
}

特性

  • 支持结构体属性的注入,支持私有字段注入 👉🏻依赖注入介绍
  • 支持函数参数的注入,按函数参数类型注入 👉🏻依赖注入介绍
  • Provider机制,支持将外部组件注入到Goner中: 👉🏻Gone V2 Provider 机制介绍
  • 支持代码生成,自动完成组件注册加载(通过Gonectr完成)
  • 支持基于接口mock的单元测试
  • 支持微服务开发的相关Goner组件
  • 支持给Goner定义初始化方法Init()BeforeInit()
  • 支持编写服务类型的Goner:实现 Start() errorStop() error,框架会自动调用Start()和Stop()方法。
  • 支持BeforeStartAfterStartBeforeStopAfterStop等钩子函数,用于在服务启动和停止时执行自定义操作。
架构
architecture
生命周期
flow

快速开始

  1. 安装 gonectrmockgen
    go install github.com/gone-io/gonectr@latest
    go install go.uber.org/mock/mockgen@latest
    
  2. 创建一个项目
    gonectr create myproject
    
  3. 运行项目
    cd myproject
    go mod tidy
    gonectr run ./cmd/server
    

更新记录

v2.0.5
  • 新增 option:"lazy"标签,用于支持字段的延时注入,参考文档
  • 注意:使用option:"lazy"标记的字段在InitProvideInject这几个方法中不能使用;
v2.0.4
  • 新增 SetValue 函数,用于统一处理各种类型的配置值
  • 重构原有的类型处理逻辑,使用反射提高通用性
v2.0.3
v2.0.0

v2版本做了大量更新,去掉不必要的概念,使用前请参考:Gone@v2 使用说明Gone 从 v1 到 v2 的更新分析

v1.2.1
  • 定义 gone.Provider,一个工厂函数用于将 不是 Goner 的外部组件(结构体、结构体指针、函数、接口)注入到 属性需要注入的Goner;
  • 修复 gone.NewProviderPriest 无法为 生成接口类型的gone.Provider生成Priest;
  • goner/gorm编写测试代码,补齐其他测试代码;文档更新。
v1.2.0
  • 提供一种新的 gone.GonerOption,可以将按类型注入,将构造注入类型实例的任务代理给一个实现了 Suck(conf string, v reflect.Value, field reflect.StructField) errorGoner
  • 提供了一个用于实现Goner Provider的辅助函数: func NewProviderPriest[T any, P any](fn func(tagConf string, param P) (T, error)) Priest
  • goner/xorm 集群模式提供策略配置的方案;
  • 完善goner/gorm代码 和 做功能测试,支持多种数据库的接入。
v1.1.1
  • goner/xorm 支持集群 和 多数据库,最新文档:https://goner.fun/zh/references/xorm.html
  • 新增 goner/gorm,封装gorm.io/gorm,用于数据库的访问,暂时只支持mysql,完善中...

贡献

如果您发现了错误或有功能请求,可以随时提交问题 ,同时欢迎提交拉取请求

联系方式

如果您有任何问题,欢迎通过以下方式联系我们:

许可证

gone 在 MIT 许可证下发布,详情请参阅 LICENSE 文件。

Documentation

Index

Constants

View Source
const (
	GonerNameNotFound   = 1001
	GonerTypeNotFound   = 1002
	CircularDependency  = 1003
	GonerTypeNotMatch   = 1004
	ConfigError         = 1005
	NotSupport          = 1006
	LoadedError         = 1007
	FailInstall         = 1008
	InjectError         = 1009
	ProviderError       = 1010
	StartError          = 1011
	DbRollForPanicError = 1012
	PanicError          = 1013
)

Error Code:1001~1999 used for gone framework.

View Source
const ConfigureName = "configure"
View Source
const (
	DefaultProviderName = "core-provider"
)
View Source
const GONE = "GONE"
View Source
const LoggerName = "gone-logger"
View Source
const Version = "v2.0.5"

Variables

View Source
var Default = NewApp()
View Source
var UnsupportedError = NewInnerError("Unsupported type by EnvConfigure", ConfigError)

Functions

func BlackMagic

func BlackMagic(v reflect.Value) reflect.Value

func End

func End()

End triggers application termination It terminates the application by sending a SIGINT signal to the default Application instance This is a convenience method equivalent to calling Default.End()

func GetFuncName

func GetFuncName(f any) string

GetFuncName get function name

func GetInterfaceType

func GetInterfaceType[T any](t *T) reflect.Type

GetInterfaceType get interface type

func GetTypeName

func GetTypeName(t reflect.Type) string

GetTypeName returns a string representation of a reflect.Type, including package path for named types. For arrays, slices, maps and pointers it recursively formats the element types. For interfaces and structs it includes the package path if available. For unnamed types it returns a basic representation like "interface{}" or "struct{}".

func IsCompatible

func IsCompatible(t reflect.Type, goner any) bool

IsCompatible checks if a goner object is compatible with a given type t. For interface types, checks if goner implements the interface. For other types, checks for exact type equality.

func IsError

func IsError(err error, code int) bool

func PanicTrace

func PanicTrace(kb int, skip int) []byte

PanicTrace captures and formats a stack trace for error reporting. Parameters:

  • kb: size of stack buffer in KB (actual size will be kb * 1024 bytes)
  • skip: number of stack frames to skip from the top

Returns formatted stack trace as bytes, trimmed to relevant section starting from caller and excluding goroutine headers.

func ParseGoneTag

func ParseGoneTag(tag string) (name string, extend string)

ParseGoneTag parses a gone tag string in the format "name,extend" into name and extend parts. The name part is used to identify the goner, while extend part contains additional configuration. For example:

  • "myGoner" returns ("myGoner", "")
  • "myGoner,config=value" returns ("myGoner", "config=value")

func RemoveRepeat

func RemoveRepeat[T comparable](list []T) []T

RemoveRepeat removes duplicate pointers from a slice of pointers to type T. It preserves the order of first occurrence of each pointer.

func Run

func Run(fn any)

func RunTest

func RunTest(fn any, priests ...LoadFunc)

RunTest Deprecated, use Test instead

func SafeExecute

func SafeExecute(fn func() error) (err error)

SafeExecute 执行可能会触发panic的函数并将panic转换为error

func Serve

func Serve()

func SetPointerValue added in v2.0.6

func SetPointerValue(v any, value string) error

SetPointerValue sets the value of a pointer to a Go type based on the provided value and environment variable.

func SetValue added in v2.0.4

func SetValue(rv reflect.Value, v any, value string) error

SetValue sets the value of a pointer to a Go type based on the provided value and environment variable. Deprecated use SetPointerValue or SetValueByReflect instead

func SetValueByReflect added in v2.0.6

func SetValueByReflect(rv reflect.Value, value string) error

SetValueByReflect sets the value of a pointer to a Go type based on the provided value and environment variable.

func SortCoffins

func SortCoffins(coffins []*coffin)

SortCoffins sorts a slice of coffins by their order

func TagStringParse

func TagStringParse(conf string) (map[string]string, []string)

TagStringParse parses a tag string in the format "key1=value1,key2=value2" into a map and ordered key slice. It splits the string by commas, then splits each part into key-value pairs by "=". Returns:

  • map[string]string: Contains all key-value pairs from the tag string
  • []string: Contains keys in order of appearance, with duplicates removed

func Test

func Test(fn any)

Test for run tests

Types

type AfterStart

type AfterStart func(Process)

AfterStart is a hook function type that can be injected into Goners to register callbacks that will execute after the application starts.

Example usage: ```go

type XGoner struct {
    Flag
    after AfterStart `gone:"*"` // Inject the AfterStart hook
}

func (x *XGoner) Init() error {
    // Register a callback to run after application start
    x.after(func() {
        fmt.Println("after start")
    })
    return nil
}

```

The registered callbacks will be executed in registration order after all daemons have been started. This allows components to perform tasks that require all services to be running.

type AfterStartProvider

type AfterStartProvider struct {
	Flag
	// contains filtered or unexported fields
}

AfterStartProvider provides the AfterStart hook registration function. This provider allows other components to register functions to be called after application start.

func (*AfterStartProvider) Provide

func (s *AfterStartProvider) Provide() (AfterStart, error)

type AfterStop

type AfterStop func(Process)

AfterStop is a hook function type that can be injected into Goners to register callbacks that will execute after the application stops.

Example usage: ```go

type XGoner struct {
    Flag
    after AfterStop `gone:"*"` // Inject the AfterStop hook
}

func (x *XGoner) Init() error {
    // Register a callback to run after application stop
    x.after(func() {
        fmt.Println("after stop")
    })
    return nil
}

```

The registered callbacks will be executed in registration order after all daemons have been stopped. This allows components to perform final cleanup tasks after all services have been shut down.

type AfterStopProvider

type AfterStopProvider struct {
	Flag
	// contains filtered or unexported fields
}

AfterStopProvider provides the AfterStop hook registration function. This provider allows other components to register functions to be called after application stop.

func (*AfterStopProvider) Provide

func (s *AfterStopProvider) Provide() (AfterStop, error)

type Application

type Application struct {
	Flag
	// contains filtered or unexported fields
}

func Load

func Load(goner Goner, options ...Option) *Application

func Loads

func Loads(loads ...LoadFunc) *Application

func NewApp

func NewApp(loads ...LoadFunc) *Application

NewApp creates and initializes a new Application instance. It creates an empty Application struct and calls init() to: 1. Initialize signal channel 2. Create new Core 3. Load core components like providers and default configure Returns the initialized Application instance ready for use.

func Prepare

func Prepare(loads ...LoadFunc) *Application

Prepare is alias for NewApp

func (*Application) AfterStart

func (s *Application) AfterStart(fn Process) *Application

AfterStart registers a function to be called after starting the application. The function will be executed after all daemons have been started. Returns the Application instance for method chaining.

func (*Application) AfterStop

func (s *Application) AfterStop(fn Process) *Application

AfterStop registers a function to be called after stopping the application. The function will be executed after all daemons have been stopped. Returns the Application instance for method chaining.

func (*Application) BeforeStart

func (s *Application) BeforeStart(fn Process) *Application

BeforeStart registers a function to be called before starting the application. The function will be executed before any daemons are started. Returns the Application instance for method chaining.

func (*Application) BeforeStop

func (s *Application) BeforeStop(fn Process) *Application

BeforeStop registers a function to be called before stopping the application. The function will be executed before any daemons are stopped. Returns the Application instance for method chaining.

func (*Application) End

func (s *Application) End() *Application

End triggers application termination by sending a SIGINT signal. Returns the Application instance for method chaining.

func (*Application) Load

func (s *Application) Load(goner Goner, options ...Option) *Application

Load loads a Goner into the Application's loader with optional configuration options. It wraps the Core.Load() method and panics if loading fails.

Parameters:

  • goner: The Goner instance to load
  • options: Optional configuration options for the Goner

Available Options:

  • Name(name string): Set custom name for the Goner
  • IsDefault(): Mark this Goner as the default implementation
  • OnlyForName(): Only register by name, not as provider
  • ForceReplace(): Replace existing Goner with same name/type
  • Order(order int): Set initialization order (lower runs first)
  • FillWhenInit(): Fill dependencies during initialization

Returns the Application instance for method chaining

func (*Application) Loads

func (s *Application) Loads(loads ...LoadFunc) *Application

Loads executes multiple LoadFuncs in sequence to configure the Application Parameters:

  • loads: Variadic LoadFunc parameters that will be executed in order

Each LoadFunc typically loads configurations or components. If any LoadFunc fails during execution, it will trigger a panic.

Returns:

  • *Application: Returns the Application instance itself for method chaining

func (*Application) Run

func (s *Application) Run(fn ...any)

Run initializes the application, injects dependencies into the provided function, executes it, and then performs cleanup. The function can have dependencies that will be automatically injected. Panics if dependency injection or execution fails.

Parameters:

  • fn: The function to execute with injected dependencies

func (*Application) Serve

func (s *Application) Serve()

Serve initializes the application, starts all daemons, and waits for termination signal. After receiving termination signal, performs cleanup by stopping all daemons.

func (*Application) Test

func (s *Application) Test(fn any)

func (*Application) WaitEnd

func (s *Application) WaitEnd() *Application

WaitEnd blocks until the application receives a termination signal (SIGINT, SIGTERM, or SIGQUIT). Returns the Application instance for method chaining.

type BError

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

BError Business error implementation

func (*BError) Code

func (e *BError) Code() int

func (*BError) Data

func (e *BError) Data() any

func (*BError) Error

func (e *BError) Error() string

func (*BError) GetStatusCode

func (e *BError) GetStatusCode() int

func (*BError) Msg

func (e *BError) Msg() string

func (*BError) SetMsg

func (e *BError) SetMsg(msg string)

type BeforeInitiator

type BeforeInitiator interface {
	BeforeInit() error
}

BeforeInitiator interface defines components that need pre-initialization before regular initialization. Components implementing this interface will have their BeforeInit() method called during Gone's initialization phase, before dependencies are filled and before Init() is called.

The BeforeInit() method should: - Perform any setup needed before dependencies are injected - Initialize basic internal state that doesn't depend on other components - Return an error if pre-initialization fails

Example usage:

type MyComponent struct {
    gone.Flag
    config *Config
}

func (c *MyComponent) BeforeInit() error {
    // Setup basic state before dependencies are filled
    c.config = &Config{}
    return nil
}

type BeforeInitiatorNoError

type BeforeInitiatorNoError interface {
	BeforeInit()
}

BeforeInitiatorNoError interface defines components that need pre-initialization but don't return errors. Similar to BeforeInitiator interface, but BeforeInit() does not return an error. Components implementing this interface will have their BeforeInit() method called during Gone's initialization phase, before dependencies are filled and before Init() is called.

The BeforeInit() method should: - Perform any setup needed before dependencies are injected - Initialize basic internal state that doesn't depend on other components - Handle errors internally rather than returning them

Example usage:

type MyComponent struct {
    gone.Flag
    config *Config
}

func (c *MyComponent) BeforeInit() {
    // Setup basic state before dependencies are filled
    c.config = &Config{}
}

type BeforeStart

type BeforeStart func(Process)

BeforeStart is a hook function type that can be injected into Goners to register callbacks that will execute before the application starts.

Example usage: ```go

type XGoner struct {
    Flag
    before BeforeStart `gone:"*"` // Inject the BeforeStart hook
}

func (x *XGoner) Init() error {
    // Register a callback to run before application start
    x.before(func() {
        fmt.Println("before start")
    })
    return nil
}

```

The registered callbacks will be executed in registration order before any daemons are started. This allows components to perform initialization tasks that must complete before the application begins its main operations.

type BeforeStartProvider

type BeforeStartProvider struct {
	Flag
	// contains filtered or unexported fields
}

BeforeStartProvider provides the BeforeStart hook registration function. This provider allows other components to register functions to be called before application start.

func (*BeforeStartProvider) Provide

func (s *BeforeStartProvider) Provide() (BeforeStart, error)

type BeforeStop

type BeforeStop func(Process)

BeforeStop is a hook function type that can be injected into Goners to register callbacks that will execute before the application stops.

Example usage: ```go

type XGoner struct {
    Flag
    before BeforeStop `gone:"*"` // Inject the BeforeStop hook
}

func (x *XGoner) Init() error {
    // Register a callback to run before application stop
    x.before(func() {
        fmt.Println("before stop")
    })
    return nil
}

```

The registered callbacks will be executed in registration order before any daemons are stopped. This allows components to perform cleanup tasks while services are still running.

type BeforeStopProvider

type BeforeStopProvider struct {
	Flag
	// contains filtered or unexported fields
}

BeforeStopProvider provides the BeforeStop hook registration function. This provider allows other components to register functions to be called before application stop.

func (*BeforeStopProvider) Provide

func (s *BeforeStopProvider) Provide() (BeforeStop, error)

type BusinessError

type BusinessError interface {
	Error
	Data() any
}

BusinessError which has data, and which is used for Business error

func NewBusinessError

func NewBusinessError(msg string, ext ...any) BusinessError

NewBusinessError creates a business error with a message, optional error code and data. Parameters:

  • msg: error message
  • ext: optional parameters:
  • ext[0]: error code (int)
  • ext[1]: additional error data (any type)

type Component

type Component = Goner

Component is an alias for Goner.

type ConfigProvider

type ConfigProvider struct {
	Flag
	// contains filtered or unexported fields
}

ConfigProvider implements a provider for injecting configuration values It uses an underlying Configure implementation to retrieve values

func (*ConfigProvider) GonerName

func (s *ConfigProvider) GonerName() string

GonerName returns the provider name "config" used for registration

func (*ConfigProvider) Init

func (s *ConfigProvider) Init()

func (*ConfigProvider) Provide

func (s *ConfigProvider) Provide(tagConf string, t reflect.Type) (any, error)

Provide implements the provider interface to inject configuration values Parameters:

  • tagConf: The tag configuration string containing key and default value
  • t: The reflect.Type of the value to provide

Returns:

  • The configured value of type t
  • Error if configuration fails

type Configure

type Configure interface {
	Get(key string, v any, defaultVal string) error
}

Configure defines the interface for configuration providers Get retrieves a configuration value by key, storing it in v, with a default value if not found

type Core

type Core struct {
	Flag
	// contains filtered or unexported fields
}

func NewCore

func NewCore() *Core

NewCore creates and initializes a new Core instance. It initializes the internal maps for tracking dependencies by name and type, and loads itself as a Goner to enable self-injection. Returns a pointer to the initialized Core.

func (*Core) Check

func (s *Core) Check() ([]dependency, error)

Check performs dependency validation and determines initialization order: 1. Collects all dependencies between components 2. Validates there are no circular dependencies 3. Determines optimal initialization order based on dependencies 4. Returns ordered list of components to initialize and any validation errors

func (*Core) GetGonerByName

func (s *Core) GetGonerByName(name string) any

func (*Core) GetGonerByType

func (s *Core) GetGonerByType(t reflect.Type) any

func (*Core) GonerName

func (s *Core) GonerName() string

func (*Core) InjectFuncParameters

func (s *Core) InjectFuncParameters(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (args []reflect.Value, err error)

InjectFuncParameters injects parameters into a function by: 1. Using injectBefore hook if provided 2. Using Core's Provide method to get dependencies 3. Creating and filling struct parameters if needed 4. Using injectAfter hook if provided Returns the injected parameter values or error if injection fails

func (*Core) InjectStruct

func (s *Core) InjectStruct(goner any) error

func (*Core) InjectWrapFunc

func (s *Core) InjectWrapFunc(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (func() []any, error)

InjectWrapFunc wraps a function with dependency injection. It injects dependencies into the function parameters and returns a wrapper function that: 1. Calls the original function with injected parameters 2. Converts return values to []any, handling nil interface values appropriately Parameters:

  • fn: The function to wrap
  • injectBefore: Optional hook called before standard injection
  • injectAfter: Optional hook called after standard injection

Returns:

  • Wrapper function that returns results as []any
  • Error if injection fails

func (*Core) Install

func (s *Core) Install() error

func (*Core) Load

func (s *Core) Load(goner Goner, options ...Option) error

Load loads a Goner into the Core with optional configuration options.

A Goner can be registered by name if it implements NamedGoner interface. If a Goner with the same name already exists: - If forceReplace option is true, the old one will be replaced - Otherwise returns LoadedError

If the Goner implements Provider interface (has Provide method), it will be registered as a provider. If a provider for the same type already exists: - If forceReplace option is true, the old one will be replaced - Otherwise returns LoadedError

Parameters:

  • goner: The Goner instance to load
  • options: Optional configuration options for the Goner

Available Options:

  • Name(name string): Set custom name for the Goner
  • IsDefault(): Mark this Goner as the default implementation
  • OnlyForName(): Only register by name, not as provider
  • ForceReplace(): Replace existing Goner with same name/type
  • Order(order int): Set initialization order (lower runs first)
  • FillWhenInit(): Fill dependencies during initialization

Returns error if:

  • Any option.Apply() fails
  • A Goner with same name already exists (without forceReplace)
  • A Provider for same type already exists (without forceReplace)

func (*Core) Loaded

func (s *Core) Loaded(key LoaderKey) bool

func (*Core) Provide

func (s *Core) Provide(tagConf string, t reflect.Type) (any, error)

type Daemon

type Daemon interface {
	Start() error
	Stop() error
}

Daemon represents a long-running service component that can be started and stopped.

Example usage: ```go

type MyDaemon struct {
    Flag
}

func (d *MyDaemon) Start() error {
    // Initialize and start the daemon
    return nil
}

func (d *MyDaemon) Stop() error {
    // Clean up and stop the daemon
    return nil
}

```

Daemons are started in order of registration when Application.Serve() or Application.start() is called. The Start() method should initialize and start the daemon's main functionality. If Start() returns an error, the application will panic.

When the application receives a termination signal, daemons are stopped in reverse order by calling their Stop() methods. The Stop() method should gracefully shut down the daemon and clean up any resources. If Stop() returns an error, the application will panic.

type EnvConfigure

type EnvConfigure struct {
	Flag
}

func (*EnvConfigure) Get

func (s *EnvConfigure) Get(key string, v any, defaultVal string) error

Get retrieves a configuration value from environment variables with fallback to default value. Supports type conversion for various Go types including string, int, float, bool, and structs.

Parameters:

  • key: Environment variable name to look up
  • v: Pointer to variable where the value will be stored
  • defaultVal: Default value if environment variable is not set

Returns error if:

  • v is not a pointer
  • Type conversion fails
  • Unsupported type is provided

type Error

type Error interface {
	error
	Msg() string
	SetMsg(msg string)
	Code() int

	GetStatusCode() int
}

Error normal error

func NewError

func NewError(code int, msg string, statusCode int) Error

NewError creates a new Error instance with the specified error code, message and HTTP status code. Parameters:

  • code: application-specific error code
  • msg: error message
  • statusCode: HTTP status code to return

func NewInnerError

func NewInnerError(msg string, code int) Error

NewInnerError creates a new InnerError with message and code, skipping one stack frame. Parameters:

  • msg: error message
  • code: error code

Returns Error interface implementation with stack trace

func NewInnerErrorSkip

func NewInnerErrorSkip(msg string, code int, skip int) Error

NewInnerErrorSkip creates a new InnerError with stack trace, skipping the specified number of stack frames. Parameters:

  • msg: error message
  • code: error code
  • skip: number of stack frames to skip when capturing stack trace

func NewInnerErrorWithParams

func NewInnerErrorWithParams(code int, format string, params ...any) Error

NewInnerErrorWithParams creates a new InnerError with formatted message and stack trace. Parameters:

  • code: error code
  • format: format string for error message
  • params: parameters to format the message string

func NewParameterError

func NewParameterError(msg string, ext ...int) Error

NewParameterError creates a parameter validation error with HTTP 400 Bad Request status. Parameters:

  • msg: error message
  • ext: optional error code (defaults to http.StatusBadRequest if not provided)

func ToError

func ToError(input any) Error

ToError converts any input to an Error type. If input is nil, returns nil. If input is already an Error type, returns it directly. For other types (error, string, or any other), wraps them in a new InnerError with stack trace.

func ToErrorWithMsg

func ToErrorWithMsg(input any, msg string) Error

ToErrorWithMsg converts any input to an Error type with an additional message prefix. If input is nil, returns nil. If msg is not empty, prepends it to the error message in format "msg: original_error_msg". Uses ToError internally to handle the input conversion.

type Flag

type Flag struct{}

Flag is a marker struct used to identify components that can be managed by the gone framework. Embedding this struct in another struct indicates that it can be used with gone's dependency injection.

type FuncInjectHook

type FuncInjectHook func(pt reflect.Type, i int, injected bool) any

FuncInjectHook is a function type used for customizing parameter injection in functions. Parameters:

  • pt: The type of parameter being injected
  • i: The index of the parameter in the function signature
  • injected: Whether the parameter has already been injected

Returns any value that should be used as the injected parameter, or nil to continue with default injection

type FuncInjector

type FuncInjector interface {
	// InjectFuncParameters injects dependencies into function parameters by:
	// 1. Using injectBefore hook if provided
	// 2. Using standard dependency injection
	// 3. Creating and filling struct parameters if needed
	// 4. Using injectAfter hook if provided
	// Returns the injected parameter values or error if injection fails
	InjectFuncParameters(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (args []reflect.Value, err error)

	// InjectWrapFunc wraps a function with dependency injection.
	// It injects dependencies into the function parameters and returns a wrapper function that:
	// 1. Calls the original function with injected parameters
	// 2. Converts return values to []any, handling nil interface values appropriately
	// Returns wrapper function and error if injection fails
	InjectWrapFunc(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (func() []any, error)
}

FuncInjector provides methods for injecting dependencies into function parameters.

The interface requires implementing:

  • InjectFuncParameters: Injects dependencies into function parameters
  • InjectWrapFunc: Wraps a function with dependency injection

Parameters for both methods:

  • fn: The function to inject dependencies into
  • injectBefore: Optional hook called before standard injection
  • injectAfter: Optional hook called after standard injection

Example usage:

injector := &Core{}
fn := func(svc *MyService) error {
    return nil
}

wrapped, err := injector.InjectWrapFunc(fn, nil, nil)
if err != nil {
    panic(err)
}
results := wrapped()

type FunctionProvider

type FunctionProvider[P, T any] func(tagConf string, param P) (T, error)

FunctionProvider is an experimental type that may change or be removed in future releases.

type Goner

type Goner interface {
	// contains filtered or unexported methods
}

Goner is the base interface that all components managed by Gone must implement. It acts as a marker interface to identify types that can be loaded into the Gone container.

Any struct that embeds the Flag struct automatically implements this interface. This allows Gone to verify that components are properly configured for dependency injection.

Example usage:

type MyComponent struct {
    gone.Flag  // Embeds Flag to implement Goner
}

type GonerKeeper

type GonerKeeper interface {
	// GetGonerByName retrieves a component by its name.
	// The name should match either the component's explicit name set via gone.Name() option
	// or the name returned by its GonerName() method if it implements NamedGoner.
	//
	// Parameters:
	//   - name: The name of the component to retrieve
	//
	// Returns:
	//   - any: The component instance if found, nil otherwise
	GetGonerByName(name string) any

	// GetGonerByType retrieves a component by its type.
	// The type should match either the exact type of the component or
	// an interface type that the component implements.
	//
	// Parameters:
	//   - t: The reflect.Type of the component to retrieve
	//
	// Returns:
	//   - any: The component instance if found, nil otherwise
	GetGonerByType(t reflect.Type) any
}

GonerKeeper interface defines methods for retrieving components from the Gone container. It provides dynamic access to components at runtime, allowing components to be looked up by either name or type.

The interface requires implementing:

  • GetGonerByName: Retrieves a component by its registered name
  • GetGonerByType: Retrieves a component by its type

Example usage: ```go

type MyComponent struct {
    gone.Flag
    keeper gone.GonerKeeper `gone:"*"`
}

func (m *MyComponent) Init() error {
    // Get component by name
    if svc := m.keeper.GetGonerByName("service"); svc != nil {
        // Use the service
    }

    // Get component by type
    if logger := m.keeper.GetGonerByType(reflect.TypeOf(&Logger{})); logger != nil {
        // Use the logger
    }
    return nil
}

```

type Initiator

type Initiator interface {
	Init() error
}

Initiator interface defines components that need initialization after dependencies are injected. Components implementing this interface will have their Init() method called during Gone's initialization phase. Init() is called after all dependencies are filled and BeforeInit() hooks (if any) have completed.

The Init() method should: - Perform any required setup or validation - Initialize internal state - Establish connections to external services - Return an error if initialization fails

Example usage:

type MyComponent struct {
    gone.Flag
    db *Database `gone:"*"`
}

func (c *MyComponent) Init() error {
    return c.db.Connect()
}

type InitiatorNoError

type InitiatorNoError interface {
	Init()
}

InitiatorNoError interface defines components that need initialization but don't return errors. Similar to Initiator interface, but Init() does not return an error. Components implementing this interface will have their Init() method called during Gone's initialization phase, after dependencies are filled and BeforeInit() hooks (if any) have completed.

The Init() method should: - Perform any required setup or validation - Initialize internal state - Establish connections to external services - Handle errors internally rather than returning them

Example usage:

type MyComponent struct {
    gone.Flag
    logger *Logger `gone:"*"`
}

func (c *MyComponent) Init() {
    c.logger.Info("Initializing MyComponent")
    // perform initialization...
}

type InnerError

type InnerError interface {
	Error
	Stack() []byte
}

InnerError which has stack, and which is used for Internal error

type LoadFunc

type LoadFunc func(Loader) error

LoadFunc represents a function that can load components into a Gone container. It takes a Loader interface as parameter to allow loading additional dependencies.

Example usage: ```go

func loadComponents(l Loader) error {
    if err := l.Load(&ServiceA{}); err != nil {
        return err
    }
    if err := l.Load(&ServiceB{}); err != nil {
        return err
    }
    return nil
}

```

func OnceLoad

func OnceLoad(fn LoadFunc) LoadFunc

type Loader

type Loader interface {
	// Load adds a component to the Gone container with optional configuration.
	//
	// Parameters:
	//   - goner: The component to load. Must implement Goner interface.
	//   - options: Optional configuration for how the component should be loaded.
	//
	// Returns:
	//   - error: Any error that occurred during loading
	Load(goner Goner, options ...Option) error

	// Loaded checks if a component identified by the given LoaderKey has been loaded.
	//
	// Parameters:
	//   - LoaderKey: The unique identifier for the component to check.
	//
	// Returns:
	//   - bool: true if the component is loaded, false otherwise
	Loaded(LoaderKey) bool
}

Loader defines the interface for loading components into the Gone container. It provides methods to load new components and check if components are already loaded.

The interface requires implementing:

  • Load: Loads a component into the container with optional configuration
  • Loaded: Checks if a component is already loaded

type LoaderKey

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

LoaderKey is a unique identifier for tracking loaded components in the Gone container. It uses an internal counter to ensure each loaded component gets a unique key.

The LoaderKey is used to: - Track which components have been loaded - Prevent duplicate loading of components - Provide a way to check component load status

func GenLoaderKey

func GenLoaderKey() LoaderKey

GenLoaderKey will return a brand new, never-before-used LoaderKey

type Logger

type Logger interface {
	Infof(msg string, args ...any)
	Errorf(msg string, args ...any)
	Warnf(msg string, args ...any)
	Debugf(msg string, args ...any)

	GetLevel() LoggerLevel
	SetLevel(level LoggerLevel)
}

func GetDefaultLogger

func GetDefaultLogger() Logger

type LoggerLevel

type LoggerLevel int8
const (
	DebugLevel LoggerLevel = -1
	InfoLevel  LoggerLevel = 0
	WarnLevel  LoggerLevel = 1
	ErrorLevel LoggerLevel = 2
)

type NamedGoner

type NamedGoner interface {
	Goner
	GonerName() string
}

NamedGoner extends the Goner interface to add naming capability to components. Components implementing this interface can be registered and looked up by name in the Gone container.

The Name() method should return a unique string identifier for the component. This name can be used when: - Loading the component with explicit name - Looking up dependencies by name using `gone:"name"` tags - Registering multiple implementations of the same interface

Example usage:

type MyNamedComponent struct {
    gone.Flag
}

func (c *MyNamedComponent) GonerName() string {
    return "myComponent"
}

type NamedProvider

type NamedProvider interface {
	NamedGoner
	Provide(tagConf string, t reflect.Type) (any, error)
}

NamedProvider is an interface for providers that can create dependencies based on name and type. It extends NamedGoner to support named component registration and provides a more flexible Provide method that can create dependencies of any type.

The interface requires:

  • Embedding the NamedGoner interface to support named component registration
  • Implementing Provide() to create dependencies based on tag config and requested type

Parameters for Provide:

  • tagConf: Configuration string from the struct tag that requested this dependency
  • t: The `reflect.Type` of the dependency being requested

Returns:

  • any: The created dependency instance of the requested type
  • error: Any error that occurred during creation

Example usage:

type ConfigProvider struct {
    gone.Flag
}

func (p *ConfigProvider) Provide(tagConf string, t reflect.Type) (any, error) {
    // Create and return instance based on t
    return &Config{}, nil
}

type NoneParamProvider

type NoneParamProvider[T any] interface {
	Goner
	Provide() (T, error)
}

NoneParamProvider is a simplified Provider interface for components that provide dependencies without requiring tag configuration. Like Provider[T], this interface is not directly dependent on Gone's implementation but serves as a guide for writing simpler providers when tag configuration is not needed.

Type Parameters:

  • T: The type of dependency this provider creates

The interface requires:

  • Embedding the Goner interface to mark it as a Gone component
  • Implementing Provide() to create and return instances of type T

Returns:

  • T: The created dependency instance
  • error: Any error that occurred during creation

Example usage:

type BeforeStartProvider struct {
    gone.Flag
    preparer *Application
}

func (p *BeforeStartProvider) Provide() (BeforeStart, error) {
    return p.preparer.beforeStart, nil
}

type Option

type Option interface {
	Apply(c *coffin) error
}

Option is an interface for configuring Goners loaded into the gone framework.

func ForceReplace

func ForceReplace() Option

ForceReplace returns an Option that allows replacing loaded Goners with the same name or type. When loading a Goner with this option: - If a Goner with the same name already exists, it will be replaced - If a provider for the same type already exists, it will be replaced

Example usage:

gone.Load(&MyService{}, gone.GonerName("service"), gone.ForceReplace())
// This will replace any existing Goner named "service"

func HighStartPriority

func HighStartPriority() Option

func IsDefault

func IsDefault(objPointers ...any) Option

IsDefault returns an Option that marks a Goner as the default implementation for its type. When multiple Goners of the same type exist, the default one will be used for injection if no specific name is requested.

Example usage:

gone.Load(&EnvConfigure{}, gone.IsDefault())

This marks EnvConfigure as the default implementation to use when injecting its interface type.

func LazyFill

func LazyFill() Option

LazyFill returns an Option that marks a Goner as lazy-filled. When this option is used, the Goner will be filled at last.

Example usage:

gone.Load(&MyService{}, gone.GonerName("service"), gone.LazyFill())

func LowStartPriority

func LowStartPriority() Option

func MediumStartPriority

func MediumStartPriority() Option

func Name

func Name(name string) Option

Name returns an Option that sets a custom name for a Goner. Components can be looked up by this name when injecting dependencies.

Example usage:

gone.Load(&EnvConfigure{}, gone.GonerName("configure"))

Parameters:

  • name: String identifier to use for this Goner

func OnlyForName

func OnlyForName() Option

OnlyForName returns an Option that marks a Goner as only available for name-based injection. When this option is used, the Goner will not be registered as a type provider, meaning it can only be injected by explicitly referencing its name.

Example usage:

gone.Load(&EnvConfigure{}, gone.GonerName("configure"), gone.OnlyForName())
// Now EnvConfigure can only be injected using `gone:"configure"` tag
// And not through interface type matching

func Order

func Order(order int) Option

Order returns an Option that sets the start order for a Goner. Components with lower order values will be started before those with higher values. This can be used to control started sequence when specific ordering is required.

Example usage:

gone.Load(&Database{}, gone.Order(1))  // started first
gone.Load(&Service{}, gone.Order(2))   // started second

Parameters:

  • order: Integer value indicating relative started order

type Preparer

type Preparer = Application

Preparer is a type alias for Application, representing the main entry point for application setup and execution.

type Process

type Process func()

Process represents a function that performs some operation without taking parameters or returning values. It is commonly used for hook functions in the application lifecycle, such as BeforeStart, AfterStart, BeforeStop and AfterStop hooks.

Example usage: ```go

type XGoner struct {
    Flag
    beforeStart BeforeStart `gone:"*"`
}

func (x *XGoner) Init() error {
    x.beforeStart(func() {
        // This is a Process function
        fmt.Println("Before application starts")
    })
    return nil
}

```

type Provider

type Provider[T any] interface {
	Goner
	Provide(tagConf string) (T, error)
}

Provider is a generic interface for components that can provide dependencies of type T. While not directly dependent on Gone's implementation, this interface helps developers write correct dependency providers that can be registered in the Gone container.

Type Parameters:

  • T: The type of dependency this provider creates

The interface requires:

  • Embedding the Goner interface to mark it as a Gone component
  • Implementing Provide() to create and return instances of type T

Parameters for Provide:

  • tagConf: Configuration string from the struct tag that requested this dependency

Returns:

  • T: The created dependency instance
  • error: Any error that occurred during creation

Example usage:

type ConfigProvider struct {
    gone.Flag
}

func (p *ConfigProvider) Provide(tagConf string) (*Config, error) {
    return &Config{}, nil
}

type StructFieldInjector

type StructFieldInjector interface {
	NamedGoner
	Inject(tagConf string, field reflect.StructField, fieldValue reflect.Value) error
}

StructFieldInjector is an interface for components that can inject dependencies into struct fields. It extends NamedGoner to support named component registration and provides a method to inject dependencies into struct fields based on tag configuration and field information.

The interface requires:

  • Embedding the NamedGoner interface to support named component registration
  • Implementing Inject() to inject dependencies into struct fields

Parameters for Inject:

  • tagConf: Configuration string from the struct tag that requested this dependency
  • field: The `reflect.StructField` that requires injection

type StructInjector

type StructInjector interface {
	// InjectStruct performs dependency injection on the provided Goner struct.
	// It scans the struct's fields for `gone` tags and injects the appropriate dependencies.
	//
	// Parameters:
	//   - goner: The struct instance to inject dependencies into. Must implement Goner interface.
	//
	// Returns:
	//   - error: Any error that occurred during injection
	InjectStruct(goner any) error
}

StructInjector defines the interface for components that can inject dependencies into struct fields. It provides a single method to perform dependency injection on struct instances that implement the Goner interface.

The interface requires implementing:

  • InjectStruct: Injects dependencies into struct fields based on gone tags

Example usage: ```go

type MyGoner struct {
    Flag
    Service *MyService `gone:"*"`  // Field to be injected
}

injector := &Core{}
goner := &MyGoner{}
err := injector.InjectStruct(goner)
if err != nil {
    panic(err)
}
// MyGoner.Service is now injected

```

The InjectStruct method analyzes the struct's fields, looking for `gone` tags, and injects the appropriate dependencies based on the tag configuration.

type TestFlag

type TestFlag interface {
	// contains filtered or unexported methods
}

type XProvider

type XProvider[T any] struct {
	Flag
	// contains filtered or unexported fields
}

XProvider is an experimental type that may change or be removed in future releases.

func WrapFunctionProvider

func WrapFunctionProvider[P, T any](fn FunctionProvider[P, T]) *XProvider[T]

WrapFunctionProvider is an experimental function that may change or be removed in future releases.

func (*XProvider[T]) Provide

func (p *XProvider[T]) Provide(tagConf string) (T, error)

Directories

Path Synopsis
mock module

Jump to

Keyboard shortcuts

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