gone

package module
v2.2.4 Latest Latest
Warning

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

Go to latest
Published: May 28, 2025 License: MIT Imports: 18 Imported by: 55

README ΒΆ

EnglishΒ  |  δΈ­ζ–‡

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

logo

πŸš€ Gone - Lightweight Dependency Injection Framework for Go

πŸ’‘ Framework Introduction

Gone is a lightweight dependency injection framework based on Golang tags, implementing component dependency management through concise annotations. Here is a typical usage example (a struct embedded with gone.Flag, which we call Goner):

type Dep struct {
    gone.Flag
    Name string
}

type Component struct {
    gone.Flag
    dep *Dep        `gone:"*"` //Dependency injection
    log gone.Logger `gone:"*"` //Inject gone.Logger

    // Inject configuration, get value from environment variable GONE_NAME; 
    // if using components like goner/viper, values can be obtained from config 
    // files or config centers.
    // Reference documentation: https://github.com/gone-io/goner
    name string     `gone:"config:name"`
}

func (c *Component) Init() {
    c.log.Infof(c.dep.Name) //Use dependency
    c.log.Infof(c.name) //Use configuration
}

✨ Core Features

  • Comprehensive Dependency Injection Support
    • Struct field injection (supports private fields)
    • Function parameter injection (auto-matching by type)
    • Configuration parameter injection (supports environment variables, config centers and config files)
    • Third-party component injection (via Provider mechanism) πŸ‘‰ Detailed Documentation
  • Supports defining initialization methods, service start/stop methods and related lifecycle hook functions for Goners, enabling automated service management and custom operations.
  • Provides ecosystem goner components supporting configuration, logging, database, LLM, observability and more.
  • Provides scaffolding tool gonectl supporting project creation, component management, code generation, test mocking, compilation and running.
Architecture
architecture
Lifecycle
flow

🏁 Quick Start

Environment Preparation
  1. Install required tools
go install github.com/gone-io/gonectl@latest
go install go.uber.org/mock/mockgen@latest
Create Project
gonectl create myproject
cd myproject
Run Project
go mod tidy
gonectl run ./cmd/server

More Documents

Release Notes

πŸ‘‰πŸ» https://github.com/gone-io/gone/releases

Contribution

If you find any bugs or have feature requests, feel free to submit an issue or submit a pull request.

Contact

If you have any questions, welcome to contact us through:

License

gone is released under the MIT License, see LICENSE for details.

Documentation ΒΆ

Overview ΒΆ

Package gone is a generated GoMock package.

Package gone is a generated GoMock package.

Package gone is a generated GoMock package.

Package gone is a generated GoMock package.

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.2.4"

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 safely executes a function and captures any panics that occur during execution. It converts panics into error returns, allowing for graceful error handling in code that might panic.

Parameters:

  • fn: The function to execute safely. This function should return an error or nil.

Returns:

  • error: The error returned by fn, or a new InnerError if a panic occurred during execution.

Example usage: ```go

func riskyOperation() error {
    // Code that might panic
    return nil
}

// Execute the risky operation safely
err := SafeExecute(riskyOperation)
if err != nil {
    // Handle the error or panic gracefully
}

```

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

func ToErrorf ΒΆ added in v2.2.3

func ToErrorf(input any, format string, params ...any) error

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 load goner for Application Parameters:

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

Each LoadFunc typically loads goner 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 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 a function, which first parameter is tagConf, and second parameter is a struct that can be injected. And the function must return a T type value and error.

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
}

func WarpThirdComponent ΒΆ added in v2.2.3

func WarpThirdComponent[T any](t T) Goner

WarpThirdComponent can wrap a third component to a Goner Provider which can make third component to inject Goners.

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

	GetGonerByPattern(t reflect.Type, pattern string) []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 Keeper ΒΆ added in v2.2.3

type Keeper = GonerKeeper

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 BuildSingProviderLoadFunc ΒΆ added in v2.0.12

func BuildSingProviderLoadFunc[P, T any](fn FunctionProvider[P, T], options ...Option) LoadFunc

BuildSingProviderLoadFunc creates a LoadFunc that wraps a FunctionProvider and ensures it's loaded only once per Loader instance. It combines the functionality of BuildOnceLoad and WrapFunctionProvider to create a reusable loader function.

Parameters:

  • fn: The FunctionProvider to be wrapped. This function will be converted to a provider component.
  • options: Optional configuration for how the provider should be loaded.

Returns:

  • LoadFunc: A wrapped function that loads the provider only once per Loader instance.

Example usage: ```go

func createService(config string, param struct {
		receiveInjected InjectedRepo `gone:"*"`
	}) (Service, error) {
	// Create and return a service instance using the config and repository
	return &ServiceImpl{repo: param.receiveInjected, config: config}, nil
}

// Create a loader function that will only load the service provider once serviceLoader := BuildSingProviderLoadFunc(createService) // Load the service provider into the container NewApp().Loads(serviceLoader)

```

func BuildThirdComponentLoadFunc ΒΆ added in v2.0.12

func BuildThirdComponentLoadFunc[T any](component T, options ...Option) LoadFunc

BuildThirdComponentLoadFunc creates a LoadFunc that registers an existing component into the container. It wraps the component in a simple provider function and ensures it's loaded only once per Loader instance.

Parameters:

  • component: The existing component instance to be registered in the container.
  • options: Optional configuration for how the component should be loaded.

Returns:

  • LoadFunc: A wrapped function that loads the component only once per Loader instance.

Example usage: ```go

type TestComponent struct {
	i int
}
// Create an existing component instance
var component TestComponent

// Create a loader function that will register the component in the container
loadFunc := BuildThirdComponentLoadFunc(&component)

// Load the component into the container
NewApp().Loads(loadFunc)

```

func OnceLoad ΒΆ

func OnceLoad(fn LoadFunc) LoadFunc

OnceLoad wraps a LoadFunc to ensure it only executes once per Loader instance. It generates a unique LoaderKey for the function and uses it to track execution status.

Parameters:

  • fn: The LoadFunc to be wrapped. This function will only be executed once per Loader.

Returns:

  • LoadFunc: A wrapped function that checks if it has already been executed before calling the original function.

Example usage: ```go

func loadComponents(l Loader) error {
    // Load dependencies...
    return nil
}

// Create a function that will only execute once per Loader
wrappedLoad := OnceLoad(loadComponents)

// First call executes loadComponents
wrappedLoad(loader)

// Second call returns nil without executing loadComponents again
wrappedLoad(loader)

``` Deprecated: this function is never need any more, because Application.Loads ensure that LoadFunc are only loaded once.

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

	MustLoadX(x any) Loader

	// MustLoad adds a component to the Gone container with optional configuration.
	// If an error occurs during loading, it panics.
	//
	// Parameters:
	//   - goner: The component to load. Must implement Goner interface.
	//   - options: Optional configuration for how the component should be loaded.
	//
	// Returns:
	//   - Loader: The Loader instance for further loading operations
	MustLoad(goner Goner, options ...Option) Loader

	// 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 MockBeforeInitiator ΒΆ added in v2.2.0

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

MockBeforeInitiator is a mock of BeforeInitiator interface.

func NewMockBeforeInitiator ΒΆ added in v2.2.0

func NewMockBeforeInitiator(ctrl *gomock.Controller) *MockBeforeInitiator

NewMockBeforeInitiator creates a new mock instance.

func (*MockBeforeInitiator) BeforeInit ΒΆ added in v2.2.0

func (m *MockBeforeInitiator) BeforeInit() error

BeforeInit mocks base method.

func (*MockBeforeInitiator) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

type MockBeforeInitiatorMockRecorder ΒΆ added in v2.2.0

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

MockBeforeInitiatorMockRecorder is the mock recorder for MockBeforeInitiator.

func (*MockBeforeInitiatorMockRecorder) BeforeInit ΒΆ added in v2.2.0

func (mr *MockBeforeInitiatorMockRecorder) BeforeInit() *gomock.Call

BeforeInit indicates an expected call of BeforeInit.

type MockBeforeInitiatorNoError ΒΆ added in v2.2.0

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

MockBeforeInitiatorNoError is a mock of BeforeInitiatorNoError interface.

func NewMockBeforeInitiatorNoError ΒΆ added in v2.2.0

func NewMockBeforeInitiatorNoError(ctrl *gomock.Controller) *MockBeforeInitiatorNoError

NewMockBeforeInitiatorNoError creates a new mock instance.

func (*MockBeforeInitiatorNoError) BeforeInit ΒΆ added in v2.2.0

func (m *MockBeforeInitiatorNoError) BeforeInit()

BeforeInit mocks base method.

func (*MockBeforeInitiatorNoError) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

type MockBeforeInitiatorNoErrorMockRecorder ΒΆ added in v2.2.0

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

MockBeforeInitiatorNoErrorMockRecorder is the mock recorder for MockBeforeInitiatorNoError.

func (*MockBeforeInitiatorNoErrorMockRecorder) BeforeInit ΒΆ added in v2.2.0

BeforeInit indicates an expected call of BeforeInit.

type MockConfigure ΒΆ added in v2.2.1

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

MockConfigure is a mock of Configure interface.

func NewMockConfigure ΒΆ added in v2.2.1

func NewMockConfigure(ctrl *gomock.Controller) *MockConfigure

NewMockConfigure creates a new mock instance.

func (*MockConfigure) EXPECT ΒΆ added in v2.2.1

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockConfigure) Get ΒΆ added in v2.2.1

func (m *MockConfigure) Get(key string, v any, defaultVal string) error

Get mocks base method.

type MockConfigureMockRecorder ΒΆ added in v2.2.1

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

MockConfigureMockRecorder is the mock recorder for MockConfigure.

func (*MockConfigureMockRecorder) Get ΒΆ added in v2.2.1

func (mr *MockConfigureMockRecorder) Get(key, v, defaultVal any) *gomock.Call

Get indicates an expected call of Get.

type MockDaemon ΒΆ added in v2.2.0

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

MockDaemon is a mock of Daemon interface.

func NewMockDaemon ΒΆ added in v2.2.0

func NewMockDaemon(ctrl *gomock.Controller) *MockDaemon

NewMockDaemon creates a new mock instance.

func (*MockDaemon) EXPECT ΒΆ added in v2.2.0

func (m *MockDaemon) EXPECT() *MockDaemonMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockDaemon) Start ΒΆ added in v2.2.0

func (m *MockDaemon) Start() error

Start mocks base method.

func (*MockDaemon) Stop ΒΆ added in v2.2.0

func (m *MockDaemon) Stop() error

Stop mocks base method.

type MockDaemonMockRecorder ΒΆ added in v2.2.0

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

MockDaemonMockRecorder is the mock recorder for MockDaemon.

func (*MockDaemonMockRecorder) Start ΒΆ added in v2.2.0

func (mr *MockDaemonMockRecorder) Start() *gomock.Call

Start indicates an expected call of Start.

func (*MockDaemonMockRecorder) Stop ΒΆ added in v2.2.0

func (mr *MockDaemonMockRecorder) Stop() *gomock.Call

Stop indicates an expected call of Stop.

type MockFuncInjector ΒΆ added in v2.2.0

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

MockFuncInjector is a mock of FuncInjector interface.

func NewMockFuncInjector ΒΆ added in v2.2.0

func NewMockFuncInjector(ctrl *gomock.Controller) *MockFuncInjector

NewMockFuncInjector creates a new mock instance.

func (*MockFuncInjector) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockFuncInjector) InjectFuncParameters ΒΆ added in v2.2.0

func (m *MockFuncInjector) InjectFuncParameters(fn any, injectBefore, injectAfter FuncInjectHook) ([]reflect.Value, error)

InjectFuncParameters mocks base method.

func (*MockFuncInjector) InjectWrapFunc ΒΆ added in v2.2.0

func (m *MockFuncInjector) InjectWrapFunc(fn any, injectBefore, injectAfter FuncInjectHook) (func() []any, error)

InjectWrapFunc mocks base method.

type MockFuncInjectorMockRecorder ΒΆ added in v2.2.0

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

MockFuncInjectorMockRecorder is the mock recorder for MockFuncInjector.

func (*MockFuncInjectorMockRecorder) InjectFuncParameters ΒΆ added in v2.2.0

func (mr *MockFuncInjectorMockRecorder) InjectFuncParameters(fn, injectBefore, injectAfter any) *gomock.Call

InjectFuncParameters indicates an expected call of InjectFuncParameters.

func (*MockFuncInjectorMockRecorder) InjectWrapFunc ΒΆ added in v2.2.0

func (mr *MockFuncInjectorMockRecorder) InjectWrapFunc(fn, injectBefore, injectAfter any) *gomock.Call

InjectWrapFunc indicates an expected call of InjectWrapFunc.

type MockGoner ΒΆ added in v2.2.0

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

MockGoner is a mock of Goner interface.

func NewMockGoner ΒΆ added in v2.2.0

func NewMockGoner(ctrl *gomock.Controller) *MockGoner

NewMockGoner creates a new mock instance.

func (*MockGoner) EXPECT ΒΆ added in v2.2.0

func (m *MockGoner) EXPECT() *MockGonerMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

type MockGonerKeeper ΒΆ added in v2.2.0

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

MockGonerKeeper is a mock of GonerKeeper interface.

func NewMockGonerKeeper ΒΆ added in v2.2.0

func NewMockGonerKeeper(ctrl *gomock.Controller) *MockGonerKeeper

NewMockGonerKeeper creates a new mock instance.

func (*MockGonerKeeper) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockGonerKeeper) GetGonerByName ΒΆ added in v2.2.0

func (m *MockGonerKeeper) GetGonerByName(name string) any

GetGonerByName mocks base method.

func (*MockGonerKeeper) GetGonerByPattern ΒΆ added in v2.2.4

func (m *MockGonerKeeper) GetGonerByPattern(t reflect.Type, pattern string) []any

GetGonerByPattern mocks base method.

func (*MockGonerKeeper) GetGonerByType ΒΆ added in v2.2.0

func (m *MockGonerKeeper) GetGonerByType(t reflect.Type) any

GetGonerByType mocks base method.

type MockGonerKeeperMockRecorder ΒΆ added in v2.2.0

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

MockGonerKeeperMockRecorder is the mock recorder for MockGonerKeeper.

func (*MockGonerKeeperMockRecorder) GetGonerByName ΒΆ added in v2.2.0

func (mr *MockGonerKeeperMockRecorder) GetGonerByName(name any) *gomock.Call

GetGonerByName indicates an expected call of GetGonerByName.

func (*MockGonerKeeperMockRecorder) GetGonerByPattern ΒΆ added in v2.2.4

func (mr *MockGonerKeeperMockRecorder) GetGonerByPattern(t, pattern any) *gomock.Call

GetGonerByPattern indicates an expected call of GetGonerByPattern.

func (*MockGonerKeeperMockRecorder) GetGonerByType ΒΆ added in v2.2.0

func (mr *MockGonerKeeperMockRecorder) GetGonerByType(t any) *gomock.Call

GetGonerByType indicates an expected call of GetGonerByType.

type MockGonerMockRecorder ΒΆ added in v2.2.0

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

MockGonerMockRecorder is the mock recorder for MockGoner.

type MockInitiator ΒΆ added in v2.2.0

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

MockInitiator is a mock of Initiator interface.

func NewMockInitiator ΒΆ added in v2.2.0

func NewMockInitiator(ctrl *gomock.Controller) *MockInitiator

NewMockInitiator creates a new mock instance.

func (*MockInitiator) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockInitiator) Init ΒΆ added in v2.2.0

func (m *MockInitiator) Init() error

Init mocks base method.

type MockInitiatorMockRecorder ΒΆ added in v2.2.0

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

MockInitiatorMockRecorder is the mock recorder for MockInitiator.

func (*MockInitiatorMockRecorder) Init ΒΆ added in v2.2.0

Init indicates an expected call of Init.

type MockInitiatorNoError ΒΆ added in v2.2.0

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

MockInitiatorNoError is a mock of InitiatorNoError interface.

func NewMockInitiatorNoError ΒΆ added in v2.2.0

func NewMockInitiatorNoError(ctrl *gomock.Controller) *MockInitiatorNoError

NewMockInitiatorNoError creates a new mock instance.

func (*MockInitiatorNoError) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockInitiatorNoError) Init ΒΆ added in v2.2.0

func (m *MockInitiatorNoError) Init()

Init mocks base method.

type MockInitiatorNoErrorMockRecorder ΒΆ added in v2.2.0

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

MockInitiatorNoErrorMockRecorder is the mock recorder for MockInitiatorNoError.

func (*MockInitiatorNoErrorMockRecorder) Init ΒΆ added in v2.2.0

Init indicates an expected call of Init.

type MockLoader ΒΆ added in v2.2.0

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

MockLoader is a mock of Loader interface.

func NewMockLoader ΒΆ added in v2.2.0

func NewMockLoader(ctrl *gomock.Controller) *MockLoader

NewMockLoader creates a new mock instance.

func (*MockLoader) EXPECT ΒΆ added in v2.2.0

func (m *MockLoader) EXPECT() *MockLoaderMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockLoader) Load ΒΆ added in v2.2.0

func (m *MockLoader) Load(goner Goner, options ...Option) error

Load mocks base method.

func (*MockLoader) Loaded ΒΆ added in v2.2.0

func (m *MockLoader) Loaded(arg0 LoaderKey) bool

Loaded mocks base method.

func (*MockLoader) MustLoad ΒΆ added in v2.2.0

func (m *MockLoader) MustLoad(goner Goner, options ...Option) Loader

MustLoad mocks base method.

func (*MockLoader) MustLoadX ΒΆ added in v2.2.0

func (m *MockLoader) MustLoadX(x any) Loader

MustLoadX mocks base method.

type MockLoaderMockRecorder ΒΆ added in v2.2.0

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

MockLoaderMockRecorder is the mock recorder for MockLoader.

func (*MockLoaderMockRecorder) Load ΒΆ added in v2.2.0

func (mr *MockLoaderMockRecorder) Load(goner any, options ...any) *gomock.Call

Load indicates an expected call of Load.

func (*MockLoaderMockRecorder) Loaded ΒΆ added in v2.2.0

func (mr *MockLoaderMockRecorder) Loaded(arg0 any) *gomock.Call

Loaded indicates an expected call of Loaded.

func (*MockLoaderMockRecorder) MustLoad ΒΆ added in v2.2.0

func (mr *MockLoaderMockRecorder) MustLoad(goner any, options ...any) *gomock.Call

MustLoad indicates an expected call of MustLoad.

func (*MockLoaderMockRecorder) MustLoadX ΒΆ added in v2.2.0

func (mr *MockLoaderMockRecorder) MustLoadX(x any) *gomock.Call

MustLoadX indicates an expected call of MustLoadX.

type MockLogger ΒΆ added in v2.2.0

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

MockLogger is a mock of Logger interface.

func NewMockLogger ΒΆ added in v2.2.0

func NewMockLogger(ctrl *gomock.Controller) *MockLogger

NewMockLogger creates a new mock instance.

func (*MockLogger) Debugf ΒΆ added in v2.2.0

func (m *MockLogger) Debugf(msg string, args ...any)

Debugf mocks base method.

func (*MockLogger) EXPECT ΒΆ added in v2.2.0

func (m *MockLogger) EXPECT() *MockLoggerMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockLogger) Errorf ΒΆ added in v2.2.0

func (m *MockLogger) Errorf(msg string, args ...any)

Errorf mocks base method.

func (*MockLogger) GetLevel ΒΆ added in v2.2.0

func (m *MockLogger) GetLevel() LoggerLevel

GetLevel mocks base method.

func (*MockLogger) Infof ΒΆ added in v2.2.0

func (m *MockLogger) Infof(msg string, args ...any)

Infof mocks base method.

func (*MockLogger) SetLevel ΒΆ added in v2.2.0

func (m *MockLogger) SetLevel(level LoggerLevel)

SetLevel mocks base method.

func (*MockLogger) Warnf ΒΆ added in v2.2.0

func (m *MockLogger) Warnf(msg string, args ...any)

Warnf mocks base method.

type MockLoggerMockRecorder ΒΆ added in v2.2.0

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

MockLoggerMockRecorder is the mock recorder for MockLogger.

func (*MockLoggerMockRecorder) Debugf ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) Debugf(msg any, args ...any) *gomock.Call

Debugf indicates an expected call of Debugf.

func (*MockLoggerMockRecorder) Errorf ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) Errorf(msg any, args ...any) *gomock.Call

Errorf indicates an expected call of Errorf.

func (*MockLoggerMockRecorder) GetLevel ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) GetLevel() *gomock.Call

GetLevel indicates an expected call of GetLevel.

func (*MockLoggerMockRecorder) Infof ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) Infof(msg any, args ...any) *gomock.Call

Infof indicates an expected call of Infof.

func (*MockLoggerMockRecorder) SetLevel ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) SetLevel(level any) *gomock.Call

SetLevel indicates an expected call of SetLevel.

func (*MockLoggerMockRecorder) Warnf ΒΆ added in v2.2.0

func (mr *MockLoggerMockRecorder) Warnf(msg any, args ...any) *gomock.Call

Warnf indicates an expected call of Warnf.

type MockNamedGoner ΒΆ added in v2.2.0

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

MockNamedGoner is a mock of NamedGoner interface.

func NewMockNamedGoner ΒΆ added in v2.2.0

func NewMockNamedGoner(ctrl *gomock.Controller) *MockNamedGoner

NewMockNamedGoner creates a new mock instance.

func (*MockNamedGoner) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockNamedGoner) GonerName ΒΆ added in v2.2.0

func (m *MockNamedGoner) GonerName() string

GonerName mocks base method.

type MockNamedGonerMockRecorder ΒΆ added in v2.2.0

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

MockNamedGonerMockRecorder is the mock recorder for MockNamedGoner.

func (*MockNamedGonerMockRecorder) GonerName ΒΆ added in v2.2.0

func (mr *MockNamedGonerMockRecorder) GonerName() *gomock.Call

GonerName indicates an expected call of GonerName.

type MockNamedProvider ΒΆ added in v2.2.0

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

MockNamedProvider is a mock of NamedProvider interface.

func NewMockNamedProvider ΒΆ added in v2.2.0

func NewMockNamedProvider(ctrl *gomock.Controller) *MockNamedProvider

NewMockNamedProvider creates a new mock instance.

func (*MockNamedProvider) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockNamedProvider) GonerName ΒΆ added in v2.2.0

func (m *MockNamedProvider) GonerName() string

GonerName mocks base method.

func (*MockNamedProvider) Provide ΒΆ added in v2.2.0

func (m *MockNamedProvider) Provide(tagConf string, t reflect.Type) (any, error)

Provide mocks base method.

type MockNamedProviderMockRecorder ΒΆ added in v2.2.0

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

MockNamedProviderMockRecorder is the mock recorder for MockNamedProvider.

func (*MockNamedProviderMockRecorder) GonerName ΒΆ added in v2.2.0

func (mr *MockNamedProviderMockRecorder) GonerName() *gomock.Call

GonerName indicates an expected call of GonerName.

func (*MockNamedProviderMockRecorder) Provide ΒΆ added in v2.2.0

func (mr *MockNamedProviderMockRecorder) Provide(tagConf, t any) *gomock.Call

Provide indicates an expected call of Provide.

type MockNoneParamProvider ΒΆ added in v2.2.0

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

MockNoneParamProvider is a mock of NoneParamProvider interface.

func NewMockNoneParamProvider ΒΆ added in v2.2.0

func NewMockNoneParamProvider[T any](ctrl *gomock.Controller) *MockNoneParamProvider[T]

NewMockNoneParamProvider creates a new mock instance.

func (*MockNoneParamProvider[T]) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockNoneParamProvider[T]) Provide ΒΆ added in v2.2.0

func (m *MockNoneParamProvider[T]) Provide() (T, error)

Provide mocks base method.

type MockNoneParamProviderMockRecorder ΒΆ added in v2.2.0

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

MockNoneParamProviderMockRecorder is the mock recorder for MockNoneParamProvider.

func (*MockNoneParamProviderMockRecorder[T]) Provide ΒΆ added in v2.2.0

func (mr *MockNoneParamProviderMockRecorder[T]) Provide() *gomock.Call

Provide indicates an expected call of Provide.

type MockProvider ΒΆ added in v2.2.0

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

MockProvider is a mock of Provider interface.

func NewMockProvider ΒΆ added in v2.2.0

func NewMockProvider[T any](ctrl *gomock.Controller) *MockProvider[T]

NewMockProvider creates a new mock instance.

func (*MockProvider[T]) EXPECT ΒΆ added in v2.2.0

func (m *MockProvider[T]) EXPECT() *MockProviderMockRecorder[T]

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockProvider[T]) Provide ΒΆ added in v2.2.0

func (m *MockProvider[T]) Provide(tagConf string) (T, error)

Provide mocks base method.

type MockProviderMockRecorder ΒΆ added in v2.2.0

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

MockProviderMockRecorder is the mock recorder for MockProvider.

func (*MockProviderMockRecorder[T]) Provide ΒΆ added in v2.2.0

func (mr *MockProviderMockRecorder[T]) Provide(tagConf any) *gomock.Call

Provide indicates an expected call of Provide.

type MockStructFieldInjector ΒΆ added in v2.2.0

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

MockStructFieldInjector is a mock of StructFieldInjector interface.

func NewMockStructFieldInjector ΒΆ added in v2.2.0

func NewMockStructFieldInjector(ctrl *gomock.Controller) *MockStructFieldInjector

NewMockStructFieldInjector creates a new mock instance.

func (*MockStructFieldInjector) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockStructFieldInjector) GonerName ΒΆ added in v2.2.0

func (m *MockStructFieldInjector) GonerName() string

GonerName mocks base method.

func (*MockStructFieldInjector) Inject ΒΆ added in v2.2.0

func (m *MockStructFieldInjector) Inject(tagConf string, field reflect.StructField, fieldValue reflect.Value) error

Inject mocks base method.

type MockStructFieldInjectorMockRecorder ΒΆ added in v2.2.0

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

MockStructFieldInjectorMockRecorder is the mock recorder for MockStructFieldInjector.

func (*MockStructFieldInjectorMockRecorder) GonerName ΒΆ added in v2.2.0

GonerName indicates an expected call of GonerName.

func (*MockStructFieldInjectorMockRecorder) Inject ΒΆ added in v2.2.0

func (mr *MockStructFieldInjectorMockRecorder) Inject(tagConf, field, fieldValue any) *gomock.Call

Inject indicates an expected call of Inject.

type MockStructInjector ΒΆ added in v2.2.0

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

MockStructInjector is a mock of StructInjector interface.

func NewMockStructInjector ΒΆ added in v2.2.0

func NewMockStructInjector(ctrl *gomock.Controller) *MockStructInjector

NewMockStructInjector creates a new mock instance.

func (*MockStructInjector) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockStructInjector) InjectStruct ΒΆ added in v2.2.0

func (m *MockStructInjector) InjectStruct(goner any) error

InjectStruct mocks base method.

type MockStructInjectorMockRecorder ΒΆ added in v2.2.0

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

MockStructInjectorMockRecorder is the mock recorder for MockStructInjector.

func (*MockStructInjectorMockRecorder) InjectStruct ΒΆ added in v2.2.0

func (mr *MockStructInjectorMockRecorder) InjectStruct(goner any) *gomock.Call

InjectStruct indicates an expected call of InjectStruct.

type MockiDependenceAnalyzer ΒΆ added in v2.2.0

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

MockiDependenceAnalyzer is a mock of iDependenceAnalyzer interface.

func NewMockiDependenceAnalyzer ΒΆ added in v2.2.0

func NewMockiDependenceAnalyzer(ctrl *gomock.Controller) *MockiDependenceAnalyzer

NewMockiDependenceAnalyzer creates a new mock instance.

func (*MockiDependenceAnalyzer) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

type MockiDependenceAnalyzerMockRecorder ΒΆ added in v2.2.0

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

MockiDependenceAnalyzerMockRecorder is the mock recorder for MockiDependenceAnalyzer.

type MockiInstaller ΒΆ added in v2.2.0

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

MockiInstaller is a mock of iInstaller interface.

func NewMockiInstaller ΒΆ added in v2.2.0

func NewMockiInstaller(ctrl *gomock.Controller) *MockiInstaller

NewMockiInstaller creates a new mock instance.

func (*MockiInstaller) EXPECT ΒΆ added in v2.2.0

EXPECT returns an object that allows the caller to indicate expected use.

type MockiInstallerMockRecorder ΒΆ added in v2.2.0

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

MockiInstallerMockRecorder is the mock recorder for MockiInstaller.

type MockiKeeper ΒΆ added in v2.2.0

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

MockiKeeper is a mock of iKeeper interface.

func NewMockiKeeper ΒΆ added in v2.2.0

func NewMockiKeeper(ctrl *gomock.Controller) *MockiKeeper

NewMockiKeeper creates a new mock instance.

func (*MockiKeeper) EXPECT ΒΆ added in v2.2.0

func (m *MockiKeeper) EXPECT() *MockiKeeperMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

type MockiKeeperMockRecorder ΒΆ added in v2.2.0

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

MockiKeeperMockRecorder is the mock recorder for MockiKeeper.

type MustLoadFunc ΒΆ added in v2.1.0

type MustLoadFunc = func(Loader)

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 a Goner Provider was created by WrapFunctionProvider.

func WrapFunctionProvider ΒΆ

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

WrapFunctionProvider can wrap a FunctionProvider to a Provider.

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