gone package - github.com/gone-io/gone/v2 - Go Packages
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.
Package gone is a generated GoMock package.
- Constants
- Variables
- func BlackMagic(v reflect.Value) reflect.Value
- func End()
- func GetFuncName(f any) string
- func GetInterfaceType[T any](t *T) reflect.Type
- func GetTypeName(t reflect.Type) string
- func IsCompatible(t reflect.Type, goner any) bool
- func IsError(err error, code int) bool
- func PanicTrace(kb int, skip int) []byte
- func ParseGoneTag(tag string) (name string, extend string)
- func RemoveRepeat[T comparable](list []T) []T
- func Run(fn ...any)
- func RunTest(fn any, priests ...LoadFunc)
- func SafeExecute(fn func() error) (err error)
- func Serve()
- func SetPointerValue(v any, value string) error
- func SetValue(rv reflect.Value, v any, value string) error
- func SetValueByReflect(rv reflect.Value, value string) error
- func SortCoffins(coffins []*coffin)
- func TagStringParse(conf string) (map[string]string, []string)
- func Test(fn any)
- func ToErrorf(input any, format string, params ...any) error
- type AfterStart
- type AfterStartProvider
- type AfterStarter
- type AfterStop
- type AfterStopProvider
- type AfterStopper
- type Application
- func (s *Application) AfterStart(fn Process) *Application
- func (s *Application) AfterStop(fn Process) *Application
- func (s *Application) BeforeStart(fn Process) *Application
- func (s *Application) BeforeStop(fn Process) *Application
- func (s *Application) End() *Application
- func (s *Application) Load(goner Goner, options ...Option) *Application
- func (s *Application) Loads(loads ...LoadFunc) *Application
- func (s *Application) Run(funcList ...any)
- func (s *Application) Serve(funcList ...any)
- func (s *Application) Test(fn any)
- func (s *Application) WaitEnd() *Application
- type BError
- type BeforeInitiator
- type BeforeInitiatorNoError
- type BeforeStart
- type BeforeStartProvider
- type BeforeStarter
- type BeforeStop
- type BeforeStopProvider
- type BeforeStopper
- type BusinessError
- type Component
- type ConfWatchFunc
- type ConfWatcher
- type ConfigProvider
- type Configure
- type Daemon
- type DynamicConfigure
- type EnvConfigure
- type Error
- func NewError(code int, msg string, statusCode int) Error
- func NewInnerError(msg string, code int) Error
- func NewInnerErrorSkip(msg string, code int, skip int) Error
- func NewInnerErrorWithParams(code int, format string, params ...any) Error
- func NewParameterError(msg string, ext ...int) Error
- func ToError(input any) Error
- func ToErrorWithMsg(input any, msg string) Error
- type Flag
- type FuncInjectHook
- type FuncInjector
- type FunctionProvider
- type Goner
- type GonerKeeper
- type Initiator
- type InitiatorNoError
- type InnerError
- type Keeper
- type LoadFunc
- type Loader
- type LoaderKey
- type Logger
- type LoggerLevel
- type MockAfterStarter
- type MockAfterStarterMockRecorder
- type MockAfterStoper
- type MockAfterStoperMockRecorder
- type MockBeforeInitiator
- type MockBeforeInitiatorMockRecorder
- type MockBeforeInitiatorNoError
- type MockBeforeInitiatorNoErrorMockRecorder
- type MockBeforeStarter
- type MockBeforeStarterMockRecorder
- type MockBeforeStoper
- type MockBeforeStoperMockRecorder
- type MockConfigure
- type MockConfigureMockRecorder
- type MockDaemon
- type MockDaemonMockRecorder
- type MockDynamicConfigure
- type MockDynamicConfigureMockRecorder
- type MockFuncInjector
- func (m *MockFuncInjector) EXPECT() *MockFuncInjectorMockRecorder
- func (m *MockFuncInjector) InjectFuncParameters(fn any, injectBefore, injectAfter FuncInjectHook) ([]reflect.Value, error)
- func (m *MockFuncInjector) InjectWrapFunc(fn any, injectBefore, injectAfter FuncInjectHook) (func() []any, error)
- type MockFuncInjectorMockRecorder
- type MockGoner
- type MockGonerKeeper
- type MockGonerKeeperMockRecorder
- type MockGonerMockRecorder
- type MockInitiator
- type MockInitiatorMockRecorder
- type MockInitiatorNoError
- type MockInitiatorNoErrorMockRecorder
- type MockLoader
- type MockLoaderMockRecorder
- type MockLogger
- func (m *MockLogger) Debugf(msg string, args ...any)
- func (m *MockLogger) EXPECT() *MockLoggerMockRecorder
- func (m *MockLogger) Errorf(msg string, args ...any)
- func (m *MockLogger) GetLevel() LoggerLevel
- func (m *MockLogger) Infof(msg string, args ...any)
- func (m *MockLogger) SetLevel(level LoggerLevel)
- func (m *MockLogger) Warnf(msg string, args ...any)
- type MockLoggerMockRecorder
- func (mr *MockLoggerMockRecorder) Debugf(msg any, args ...any) *gomock.Call
- func (mr *MockLoggerMockRecorder) Errorf(msg any, args ...any) *gomock.Call
- func (mr *MockLoggerMockRecorder) GetLevel() *gomock.Call
- func (mr *MockLoggerMockRecorder) Infof(msg any, args ...any) *gomock.Call
- func (mr *MockLoggerMockRecorder) SetLevel(level any) *gomock.Call
- func (mr *MockLoggerMockRecorder) Warnf(msg any, args ...any) *gomock.Call
- type MockNamedGoner
- type MockNamedGonerMockRecorder
- type MockNamedProvider
- type MockNamedProviderMockRecorder
- type MockNoneParamProvider
- type MockNoneParamProviderMockRecorder
- type MockProvider
- type MockProviderMockRecorder
- type MockStructFieldInjector
- type MockStructFieldInjectorMockRecorder
- type MockStructInjector
- type MockStructInjectorMockRecorder
- type MockiDependenceAnalyzer
- type MockiDependenceAnalyzerMockRecorder
- type MockiInstaller
- type MockiInstallerMockRecorder
- type MockiKeeper
- type MockiKeeperMockRecorder
- type MustLoadFunc
- type NamedGoner
- type NamedProvider
- type NoneParamProvider
- type Option
- type Preparer
- type Process
- type Provider
- type RunOption
- type StructFieldInjector
- type StructInjector
- type TestFlag
- type XProvider
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.
const (
DefaultProviderName = "core-provider"
)
Default is a singleton instance of Application, used to simplify common usage patterns.
var UnsupportedError = NewInnerError("Unsupported type by EnvConfigure", ConfigError)
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()
GetFuncName get function name
GetInterfaceType get interface type
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{}".
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.
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.
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")
RemoveRepeat removes duplicate pointers from a slice of pointers to type T. It preserves the order of first occurrence of each pointer.
Run executes one or more functions using the default application instance. These functions can have dependencies that will be automatically injected. Parameters:
- fn: A variadic list of functions to execute with injected dependencies
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
}
```
Serve starts all daemons and waits for termination signal using the default application instance. This function will start all registered daemons and block until a shutdown signal is received.
SetPointerValue sets the value of a pointer to a Go type based on the provided value and environment variable.
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
SetValueByReflect sets the value of a pointer to a Go type based on the provided value and environment variable.
func SortCoffins(coffins []*coffin)
SortCoffins sorts a slice of coffins by their order
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
Test runs tests using the default application instance. Parameters:
- fn: The test function to execute with injected dependencies
type AfterStart func(Process)
AfterStart is a HookReg 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 HookReg
}
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 struct {
Flag
}
AfterStartProvider provides the AfterStart hook registration function. This provider allows other components to register functions to be called after application start.
type AfterStarter interface {
AfterStart()
}
AfterStarter interface defines components that need to perform actions after the application starts. Components implementing this interface will have their AfterStart() method called during Gone's startup phase, after all daemons have been started successfully.
The AfterStart() method should: - Perform any setup that requires all services to be running - Register with external services or health checks - Handle errors internally since no error is returned
Example usage:
type MyComponent struct {
gone.Flag
healthCheck *HealthCheck `gone:"*"`
}
func (c *MyComponent) AfterStart() {
c.healthCheck.Register()
// perform post-start setup...
}
type AfterStop func(Process)
AfterStop is a HookReg 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 HookReg
}
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 struct {
Flag
}
AfterStopProvider provides the AfterStop hook registration function. This provider allows other components to register functions to be called after application stop.
type AfterStopper interface {
AfterStop()
}
AfterStopper interface defines components that need to perform actions after the application stops. Components implementing this interface will have their AfterStop() method called during Gone's shutdown phase, after all daemons have been stopped successfully.
The AfterStop() method should: - Perform final cleanup tasks - Release any remaining resources - Log shutdown completion - Handle errors internally since no error is returned
Example usage:
type MyComponent struct {
gone.Flag
logger *Logger `gone:"*"`
}
func (c *MyComponent) AfterStop() {
c.logger.Info("Application shutdown complete")
// perform final cleanup...
}
type Application struct {
Flag
}
Application represents the core container and orchestrator for the Gone framework. Think of it as the "command center" or "central dispatch" of your application - it's like the conductor of an orchestra who knows every musician (component), their instruments (capabilities), and how they should work together to create beautiful music (your application).
The Application acts as the central hub that: - Loads and manages all components (like a "personnel manager") - Handles dependency injection between components (like a "matchmaker") - Manages application lifecycle with hooks (like a "stage director") - Provides access to components via the GonerKeeper interface (like a "directory service")
Design Philosophy: - Single Responsibility: Each Application instance manages one complete application context - Composition over Inheritance: Built by composing various specialized components - Encapsulation: Internal complexity is hidden behind simple, intuitive interfaces
Key responsibilities: - Component registration and loading ("hiring and onboarding") - Dependency resolution and injection ("team building and collaboration") - Lifecycle management with hooks ("project management") - Graceful shutdown handling ("orderly dismissal")
func Load(goner Goner, options ...Option) *Application
Load uses the default application instance to load a Goner with optional configuration options. Parameters:
- goner: The Goner instance to load
- options: Optional configuration options for the Goner
Returns:
- *Application: Returns the default application instance for method chaining
func Loads(loads ...LoadFunc) *Application
Loads uses the default application instance to load multiple LoadFunc functions. Parameters:
- loads: One or more LoadFunc functions that will be executed in sequence
Returns:
- *Application: Returns the default application instance for method chaining
func NewApp(loads ...LoadFunc) *Application
NewApp creates and initializes a new Application instance. Think of it as "founding a new company" where LoadFuncs are like "department setup plans" that define how to establish different parts of your application. Each LoadFunc knows how to "hire" and "organize" specific types of components.
The Creation Process: - Establishes the "company headquarters" (Application instance) - Registers "department setup plans" (LoadFuncs) - Prepares the "organizational structure" for component management
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(loads ...LoadFunc) *Application
Prepare is alias for NewApp
func (s *Application) AfterStart(fn Process) *Application
AfterStart registers a function to be called after starting the application. Think of it as scheduling a "grand opening celebration" or "post-launch activities" that happen after your "business" is officially open and running. The function will be executed after all daemons have been started.
Typical Use Cases: - Success notifications and logging - Health check registrations - Monitoring and metrics setup - External service announcements
Returns the Application instance for method chaining.
func (s *Application) AfterStop(fn Process) *Application
AfterStop registers a function to be called after stopping the application. Think of it as "post-closure activities" that happen after your "business" has officially closed its doors. The function will be executed after all daemons have been stopped.
Typical Use Cases: - Final cleanup and resource release - Shutdown success logging - External service deregistration - Final state persistence
Returns the Application instance for method chaining.
func (s *Application) BeforeStart(fn Process) *Application
BeforeStart registers a function to be called before starting the application. Think of it as scheduling a "pre-opening meeting" where you can perform final preparations before your "business" officially opens its doors. The function will be executed before any daemons are started.
Typical Use Cases: - Final system checks and validations - Cache warming and data preloading - External service connections - Configuration validation
Returns the Application instance for method chaining.
func (s *Application) BeforeStop(fn Process) *Application
BeforeStop registers a function to be called before stopping the application. Think of it as scheduling "closing preparations" where you perform necessary tasks before your "business" officially closes. The function will be executed before any daemons are stopped.
Typical Use Cases: - Graceful connection closures - Data persistence and state saving - Resource cleanup and release - Shutdown notifications
Returns the Application instance for method chaining.
func (s *Application) End() *Application
End triggers application termination by sending a SIGINT signal. Think of it as the "official closing procedure" where you send the "closing signal" to initiate graceful shutdown. This method triggers application termination by sending a SIGINT signal.
Returns the Application instance for method chaining.
func (s *Application) Load(goner Goner, options ...Option) *Application
Load loads a Goner into the Application's loader with optional configuration options. Think of it as "hiring a new employee" where you bring a specific person (component) into your company (application) and give them their "employee handbook" (options). It wraps the Core.Load() method and panics if loading fails.
The Hiring Process: - Verify the candidate has proper "credentials" (implements Goner interface) - Assign them a unique "employee ID" (internal tracking) - Set up their "workspace" and "job description" (configuration) - Add them to the "company directory" (component registry)
Parameters:
- goner: The Goner instance to load - the "new hire"
- options: Optional configuration options for the Goner - the "employment terms"
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 (s *Application) Loads(loads ...LoadFunc) *Application
Loads executes multiple LoadFuncs in sequence to load goner for Application Think of it as "batch hiring" where you bring multiple new employees into your company at once, like during a "recruitment drive" or "team expansion".
The Batch Hiring Process: - Process each LoadFunc in sequence - Each LoadFunc acts like a "department setup plan" - Stop the process if any "hiring" fails
Parameters:
- loads: Variadic LoadFunc parameters that will be executed in order - the "batch of hiring plans"
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 (s *Application) Run(funcList ...any)
Run initializes the application, injects dependencies into the provided function, executes it, and then performs cleanup. Think of it as "opening your business for a specific task" - you unlock the doors, turn on all systems, perform the specific work, then properly close everything down. The function can have dependencies that will be automatically injected. Panics if dependency injection or execution fails.
The Complete Business Day Process: 1. "System setup" - Install and initialize all components 2. "Team coordination" - Collect and register lifecycle hooks 3. "Open for business" - Execute start procedures 4. "Main work" - Execute provided functions with dependency injection 5. "Proper closure" - Execute stop procedures
Parameters:
- funcList: The function to execute with injected dependencies - the "main business tasks"
func (s *Application) Serve(funcList ...any)
Serve initializes the application, starts all daemons, and waits for termination signal. Think of it as "opening your business for continuous operation" - you unlock the doors, start all services, and keep the business running until you receive a "closing signal". After receiving termination signal, performs cleanup by stopping all daemons.
The Continuous Operation Process: - Same as Run() but includes OpWaitEnd() to wait for termination signals - Ideal for long-running applications like web servers or background services
func (s *Application) Test(fn any)
Test runs the application in test mode with dependency injection. Think of it as setting up a "testing laboratory" where you can experiment with your components in a controlled environment. This method is designed for testing scenarios where you need to execute test functions with proper dependency injection.
The Testing Laboratory Process: - Loads a test flag to indicate test mode - Executes the test function using Run() with full dependency injection
Key Features: - Full dependency injection support - Simplified execution for testing purposes - Test mode indication via testFlag
func (s *Application) WaitEnd() *Application
WaitEnd blocks until the application receives a termination signal (SIGINT, SIGTERM, or SIGQUIT). Think of it as a "security guard" who watches the door and waits for the "closing time signal". This method listens for termination signals (like Ctrl+C or system shutdown) and returns when one is received, allowing for graceful shutdown procedures.
Signal Monitoring: - SIGINT: Usually triggered by Ctrl+C ("manual closing") - SIGTERM: System shutdown or process termination ("scheduled closing") - SIGQUIT: Quit signal ("emergency closing")
Returns the Application instance for method chaining.
BError Business error implementation
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 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 func(Process)
BeforeStart is a HookReg 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 HookReg
}
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 struct {
Flag
}
BeforeStartProvider provides the BeforeStart hook registration function. This provider allows other components to register functions to be called before application start.
type BeforeStarter interface {
BeforeStart()
}
BeforeStarter interface defines components that need to perform actions before the application starts. Components implementing this interface will have their BeforeStart() method called during Gone's startup phase, before any daemons are started but after all components have been initialized.
The BeforeStart() method should: - Perform any setup needed before daemons start - Initialize resources that daemons depend on - Handle errors internally since no error is returned
Example usage:
type MyComponent struct {
gone.Flag
logger *Logger `gone:"*"`
}
func (c *MyComponent) BeforeStart() {
c.logger.Info("Preparing for application start")
// perform pre-start setup...
}
type BeforeStop func(Process)
BeforeStop is a HookReg 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 HookReg
}
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 struct {
Flag
}
BeforeStopProvider provides the BeforeStop hook registration function. This provider allows other components to register functions to be called before application stop.
type BeforeStopper interface {
BeforeStop()
}
BeforeStopper interface defines components that need to perform actions before the application stops. Components implementing this interface will have their BeforeStop() method called during Gone's shutdown phase, before any daemons are stopped but after termination signal is received.
The BeforeStop() method should: - Perform cleanup tasks while all services are still running - Save important state or data - Gracefully disconnect from external services - Handle errors internally since no error is returned
Example usage:
type MyComponent struct {
gone.Flag
cache *Cache `gone:"*"`
}
func (c *MyComponent) BeforeStop() {
c.cache.Flush()
// perform pre-stop cleanup...
}
BusinessError which has data, and which is used for Business error
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)
Component is an alias for Goner.
type ConfWatchFunc func(oldVal, newVal any)
ConfWatchFunc defines the callback function for configuration changes
type ConfWatcher func(key string, callback ConfWatchFunc)
ConfWatcher which can be injected, to register a callback function to be called when the specified key changes
type ConfigProvider struct {
Flag
}
ConfigProvider implements a provider for injecting configuration values It uses an underlying Configure implementation to retrieve values
GonerName returns the provider name "config" used for registration
func (s *ConfigProvider) Init()
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
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
Daemon represents a long-running service component that can be started and stopped. Think of it as a "background service worker" that runs continuously to provide specific functionality, like a web server, database connection pool, or message queue processor.
Lifecycle Management: Daemons are started in order of registration when Application.Serve() or Application.start() is called. When the application receives a termination signal, daemons are stopped in reverse order to ensure proper cleanup and resource management.
Error Handling: - If Start() returns an error, the application will panic to prevent inconsistent state - If Stop() returns an error, the application will panic to ensure proper cleanup
Example usage: ```go
type MyDaemon struct {
gone.Flag
}
func (d *MyDaemon) Start() error {
// Initialize and start the daemon's main functionality
// Like starting a web server or opening database connections
return nil
}
func (d *MyDaemon) Stop() error {
// Gracefully shut down the daemon and clean up resources
// Like closing connections and saving state
return nil
}
```
type DynamicConfigure interface {
Configure
Notify(key string, callback ConfWatchFunc)
}
DynamicConfigure defines the interface for dynamic configuration providers
type EnvConfigure struct {
Flag
}
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
Error normal 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
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
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
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
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)
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.
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.
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.
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 interface {
InjectFuncParameters(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (args []reflect.Value, err error)
InjectWrapFunc(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (func() []any, error)
}
FuncInjector provides methods for injecting dependencies into function parameters. Think of it as an "intelligent assistant" that automatically identifies what parameters a function needs, then finds the corresponding components from the "warehouse" and automatically "feeds" them to the function. It's like ordering takeout where the delivery person automatically brings all the dishes according to your order.
The interface requires implementing:
- InjectFuncParameters: Injects dependencies into function parameters
- InjectWrapFunc: Wraps a function with dependency injection
Magic Principles:
- Parameter Recognition: Automatically analyzes function signatures to understand required parameter types
- Smart Matching: Finds matching instances from registered components
- Auto Invocation: Calls the target function with found components as parameters
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
Typical Applications:
- Controller Methods: Automatic parameter injection for web request handlers
- Utility Functions: Tool function calls requiring multiple dependencies
- Testing Scenarios: Automatic dependency assembly for test functions
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()
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.
Goner is the base interface that all components managed by Gone must implement. It acts as a "component identity card" - any component wanting to be managed by the Gone framework must hold this "identity card". This is a clever design using a private method to ensure only "official channels" can obtain this "identity card".
Any struct that embeds the Flag struct automatically implements this interface. This allows Gone to verify that components are properly configured for dependency injection. Just like getting an ID card requires going to the designated office, becoming a Goner can only be achieved by embedding the `gone.Flag` "official seal".
Design Benefits:
- Security: Prevents "counterfeit" components from entering the system
- Consistency: Ensures all components follow the same "registration" process
- Control: Framework has complete control over component lifecycle
Example usage:
type MyComponent struct {
gone.Flag // Embeds Flag to implement Goner - the "identity card"
}
GonerKeeper interface defines methods for retrieving components from the Gone container. Think of it as a super-intelligent "archive manager" who knows the "home address" of every component in the system. Whether you want to find someone by "name" or by "profession" (type), it can quickly locate them. 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
- GetGonerByPattern: Retrieves components matching a pattern
Practical Scenarios:
- Dynamic Lookup: Find specific components at runtime as needed
- Precise Location: Quickly locate target components by name or type
- Pattern Matching: Use wildcard patterns to batch retrieve components
Example usage: ```go
type MyComponent struct {
gone.Flag
keeper gone.GonerKeeper `gone:"*"`
}
func (m *MyComponent) Init() error {
// Get component by name - like looking up someone's "business card"
if svc := m.keeper.GetGonerByName("service"); svc != nil {
// Use the service
}
// Get component by type - like finding someone by "profession"
if logger := m.keeper.GetGonerByType(reflect.TypeOf(&Logger{})); logger != nil {
// Use the logger
}
return nil
}
```
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 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...
}
InnerError which has stack, and which is used for Internal error
type Keeper = GonerKeeper
LoadFunc represents a function that can load components into a Gone container. Think of it as a "professional moving company" that knows how to properly "pack" and "relocate" specific types of components into the Gone framework. Each LoadFunc knows how to correctly handle the loading process for particular component types.
LoadFunc Work Flow:
- Package Components: Prepare business components for loading
- Transport and Load: Load components into the framework through Loader
- Confirm Checklist: Return loading results (success or error)
It takes a Loader interface as parameter to allow loading additional dependencies, enabling LoadFuncs to form a tree-like structure for complex component hierarchies.
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[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)
```
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)
```
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 interface {
Load(goner Goner, options ...Option) error
MustLoadX(x any) Loader
MustLoad(goner Goner, options ...Option) Loader
Loaded(LoaderKey) bool
}
Loader defines the interface for loading components into the Gone container. Think of it as a company's "HR onboarding specialist" responsible for handling "onboarding procedures" for new components. It assigns each new component a "employee ID", establishes their "personnel file", and officially includes them in the Gone framework's "employee roster".
Onboarding Process:
- Identity Verification: Confirms component implements Goner interface (holds "ID card")
- Assign ID: Allocates unique identifier for the component
- Establish Records: Records component type, dependencies, and other information
- Archive Management: Stores component information in the framework's management system
Usage Scenarios:
- Application Startup: Batch loading of core application components
- Plugin Loading: Dynamic loading of plugin components
- Test Environment: Loading specific mock components for testing
The interface requires implementing:
- Load: Loads a component into the container with optional configuration
- MustLoad: Loads a component and panics on error (for critical components)
- MustLoadX: Flexible loading that handles both components and LoadFuncs
- Loaded: Checks if a component is already loaded
type LoaderKey struct {
}
LoaderKey is a unique identifier for tracking loaded components in the Gone container. Think of it as a "component registration number" that uses an internal counter to ensure each loaded component gets a unique identifier, like a social security number for components.
The LoaderKey is used to: - Track which components have been loaded (like a "registration database") - Prevent duplicate loading of components (avoid "double registration") - Provide a way to check component load status ("registration verification")
This ensures the framework can efficiently manage component lifecycle and prevent conflicts.
func GenLoaderKey() LoaderKey
GenLoaderKey will return a brand new, never-before-used LoaderKey
Logger Interface which can be injected and provided by gone framework core
func GetDefaultLogger() Logger
const ( DebugLevel LoggerLevel = -1 InfoLevel LoggerLevel = 0 WarnLevel LoggerLevel = 1 ErrorLevel LoggerLevel = 2 )
type MockAfterStarter struct {
Flag
}
MockAfterStarter is a mock of AfterStarter interface.
NewMockAfterStarter creates a new mock instance.
func (m *MockAfterStarter) AfterStart()
AfterStart mocks base method.
EXPECT returns an object that allows the caller to indicate expected use.
type MockAfterStarterMockRecorder struct {
}
MockAfterStarterMockRecorder is the mock recorder for MockAfterStarter.
AfterStart indicates an expected call of AfterStart.
type MockAfterStoper struct {
Flag
}
MockAfterStoper is a mock of AfterStoper interface.
NewMockAfterStoper creates a new mock instance.
func (m *MockAfterStoper) AfterStop()
AfterStop mocks base method.
func (m *MockAfterStoper) EXPECT() *MockAfterStoperMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockAfterStoperMockRecorder struct {
}
MockAfterStoperMockRecorder is the mock recorder for MockAfterStoper.
AfterStop indicates an expected call of AfterStop.
type MockBeforeInitiator struct {
Flag
}
MockBeforeInitiator is a mock of BeforeInitiator interface.
NewMockBeforeInitiator creates a new mock instance.
BeforeInit mocks base method.
EXPECT returns an object that allows the caller to indicate expected use.
type MockBeforeInitiatorMockRecorder struct {
}
MockBeforeInitiatorMockRecorder is the mock recorder for MockBeforeInitiator.
BeforeInit indicates an expected call of BeforeInit.
type MockBeforeInitiatorNoError struct {
Flag
}
MockBeforeInitiatorNoError is a mock of BeforeInitiatorNoError interface.
NewMockBeforeInitiatorNoError creates a new mock instance.
func (m *MockBeforeInitiatorNoError) BeforeInit()
BeforeInit mocks base method.
EXPECT returns an object that allows the caller to indicate expected use.
type MockBeforeInitiatorNoErrorMockRecorder struct {
}
MockBeforeInitiatorNoErrorMockRecorder is the mock recorder for MockBeforeInitiatorNoError.
BeforeInit indicates an expected call of BeforeInit.
type MockBeforeStarter struct {
Flag
}
MockBeforeStarter is a mock of BeforeStarter interface.
NewMockBeforeStarter creates a new mock instance.
func (m *MockBeforeStarter) BeforeStart()
BeforeStart mocks base method.
EXPECT returns an object that allows the caller to indicate expected use.
type MockBeforeStarterMockRecorder struct {
}
MockBeforeStarterMockRecorder is the mock recorder for MockBeforeStarter.
BeforeStart indicates an expected call of BeforeStart.
type MockBeforeStoper struct {
Flag
}
MockBeforeStoper is a mock of BeforeStoper interface.
NewMockBeforeStoper creates a new mock instance.
func (m *MockBeforeStoper) BeforeStop()
BeforeStop mocks base method.
EXPECT returns an object that allows the caller to indicate expected use.
type MockBeforeStoperMockRecorder struct {
}
MockBeforeStoperMockRecorder is the mock recorder for MockBeforeStoper.
BeforeStop indicates an expected call of BeforeStop.
type MockConfigure struct {
}
MockConfigure is a mock of Configure interface.
NewMockConfigure creates a new mock instance.
func (m *MockConfigure) EXPECT() *MockConfigureMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockConfigureMockRecorder struct {
}
MockConfigureMockRecorder is the mock recorder for MockConfigure.
Get indicates an expected call of Get.
type MockDaemon struct {
}
MockDaemon is a mock of Daemon interface.
NewMockDaemon creates a new mock instance.
func (m *MockDaemon) EXPECT() *MockDaemonMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockDaemonMockRecorder struct {
}
MockDaemonMockRecorder is the mock recorder for MockDaemon.
Start indicates an expected call of Start.
Stop indicates an expected call of Stop.
type MockDynamicConfigure struct {
Flag
}
MockDynamicConfigure is a mock of DynamicConfigure interface.
NewMockDynamicConfigure creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
Notify mocks base method.
type MockDynamicConfigureMockRecorder struct {
}
MockDynamicConfigureMockRecorder is the mock recorder for MockDynamicConfigure.
Get indicates an expected call of Get.
Notify indicates an expected call of Notify.
type MockFuncInjector struct {
}
MockFuncInjector is a mock of FuncInjector interface.
NewMockFuncInjector creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
InjectFuncParameters mocks base method.
func (m *MockFuncInjector) InjectWrapFunc(fn any, injectBefore, injectAfter FuncInjectHook) (func() []any, error)
InjectWrapFunc mocks base method.
type MockFuncInjectorMockRecorder struct {
}
MockFuncInjectorMockRecorder is the mock recorder for MockFuncInjector.
func (mr *MockFuncInjectorMockRecorder) InjectFuncParameters(fn, injectBefore, injectAfter any) *gomock.Call
InjectFuncParameters indicates an expected call of InjectFuncParameters.
InjectWrapFunc indicates an expected call of InjectWrapFunc.
type MockGoner struct {
}
MockGoner is a mock of Goner interface.
NewMockGoner creates a new mock instance.
func (m *MockGoner) EXPECT() *MockGonerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockGonerKeeper struct {
}
MockGonerKeeper is a mock of GonerKeeper interface.
NewMockGonerKeeper creates a new mock instance.
func (m *MockGonerKeeper) EXPECT() *MockGonerKeeperMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
GetGonerByName mocks base method.
GetGonerByPattern mocks base method.
GetGonerByType mocks base method.
type MockGonerKeeperMockRecorder struct {
}
MockGonerKeeperMockRecorder is the mock recorder for MockGonerKeeper.
GetGonerByName indicates an expected call of GetGonerByName.
GetGonerByPattern indicates an expected call of GetGonerByPattern.
GetGonerByType indicates an expected call of GetGonerByType.
type MockGonerMockRecorder struct {
}
MockGonerMockRecorder is the mock recorder for MockGoner.
type MockInitiator struct {
Flag
}
MockInitiator is a mock of Initiator interface.
NewMockInitiator creates a new mock instance.
func (m *MockInitiator) EXPECT() *MockInitiatorMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockInitiatorMockRecorder struct {
}
MockInitiatorMockRecorder is the mock recorder for MockInitiator.
Init indicates an expected call of Init.
type MockInitiatorNoError struct {
Flag
}
MockInitiatorNoError is a mock of InitiatorNoError interface.
NewMockInitiatorNoError creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockInitiatorNoError) Init()
Init mocks base method.
type MockInitiatorNoErrorMockRecorder struct {
}
MockInitiatorNoErrorMockRecorder is the mock recorder for MockInitiatorNoError.
Init indicates an expected call of Init.
type MockLoader struct {
}
MockLoader is a mock of Loader interface.
NewMockLoader creates a new mock instance.
func (m *MockLoader) EXPECT() *MockLoaderMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockLoader) Load(goner Goner, options ...Option) error
Load mocks base method.
Loaded mocks base method.
func (m *MockLoader) MustLoad(goner Goner, options ...Option) Loader
MustLoad mocks base method.
func (m *MockLoader) MustLoadX(x any) Loader
MustLoadX mocks base method.
type MockLoaderMockRecorder struct {
}
MockLoaderMockRecorder is the mock recorder for MockLoader.
Load indicates an expected call of Load.
Loaded indicates an expected call of Loaded.
MustLoad indicates an expected call of MustLoad.
MustLoadX indicates an expected call of MustLoadX.
type MockLogger struct {
}
MockLogger is a mock of Logger interface.
NewMockLogger creates a new mock instance.
Debugf mocks base method.
func (m *MockLogger) EXPECT() *MockLoggerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
Errorf mocks base method.
func (m *MockLogger) GetLevel() LoggerLevel
GetLevel mocks base method.
func (m *MockLogger) SetLevel(level LoggerLevel)
SetLevel mocks base method.
type MockLoggerMockRecorder struct {
}
MockLoggerMockRecorder is the mock recorder for MockLogger.
Debugf indicates an expected call of Debugf.
Errorf indicates an expected call of Errorf.
GetLevel indicates an expected call of GetLevel.
Infof indicates an expected call of Infof.
SetLevel indicates an expected call of SetLevel.
Warnf indicates an expected call of Warnf.
type MockNamedGoner struct {
}
MockNamedGoner is a mock of NamedGoner interface.
NewMockNamedGoner creates a new mock instance.
func (m *MockNamedGoner) EXPECT() *MockNamedGonerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
GonerName mocks base method.
type MockNamedGonerMockRecorder struct {
}
MockNamedGonerMockRecorder is the mock recorder for MockNamedGoner.
GonerName indicates an expected call of GonerName.
type MockNamedProvider struct {
}
MockNamedProvider is a mock of NamedProvider interface.
NewMockNamedProvider creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
GonerName mocks base method.
Provide mocks base method.
type MockNamedProviderMockRecorder struct {
}
MockNamedProviderMockRecorder is the mock recorder for MockNamedProvider.
GonerName indicates an expected call of GonerName.
Provide indicates an expected call of Provide.
type MockNoneParamProvider[T any] struct { }
MockNoneParamProvider is a mock of NoneParamProvider interface.
NewMockNoneParamProvider creates a new mock instance.
func (m *MockNoneParamProvider[T]) EXPECT() *MockNoneParamProviderMockRecorder[T]
EXPECT returns an object that allows the caller to indicate expected use.
Provide mocks base method.
type MockNoneParamProviderMockRecorder[T any] struct { }
MockNoneParamProviderMockRecorder is the mock recorder for MockNoneParamProvider.
Provide indicates an expected call of Provide.
type MockProvider[T any] struct { }
MockProvider is a mock of Provider interface.
NewMockProvider creates a new mock instance.
func (m *MockProvider[T]) EXPECT() *MockProviderMockRecorder[T]
EXPECT returns an object that allows the caller to indicate expected use.
Provide mocks base method.
type MockProviderMockRecorder[T any] struct { }
MockProviderMockRecorder is the mock recorder for MockProvider.
Provide indicates an expected call of Provide.
type MockStructFieldInjector struct {
}
MockStructFieldInjector is a mock of StructFieldInjector interface.
NewMockStructFieldInjector creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
GonerName mocks base method.
Inject mocks base method.
type MockStructFieldInjectorMockRecorder struct {
}
MockStructFieldInjectorMockRecorder is the mock recorder for MockStructFieldInjector.
GonerName indicates an expected call of GonerName.
Inject indicates an expected call of Inject.
type MockStructInjector struct {
}
MockStructInjector is a mock of StructInjector interface.
NewMockStructInjector creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
InjectStruct mocks base method.
type MockStructInjectorMockRecorder struct {
}
MockStructInjectorMockRecorder is the mock recorder for MockStructInjector.
InjectStruct indicates an expected call of InjectStruct.
type MockiDependenceAnalyzer struct {
}
MockiDependenceAnalyzer is a mock of iDependenceAnalyzer interface.
NewMockiDependenceAnalyzer creates a new mock instance.
EXPECT returns an object that allows the caller to indicate expected use.
type MockiDependenceAnalyzerMockRecorder struct {
}
MockiDependenceAnalyzerMockRecorder is the mock recorder for MockiDependenceAnalyzer.
type MockiInstaller struct {
}
MockiInstaller is a mock of iInstaller interface.
NewMockiInstaller creates a new mock instance.
func (m *MockiInstaller) EXPECT() *MockiInstallerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockiInstallerMockRecorder struct {
}
MockiInstallerMockRecorder is the mock recorder for MockiInstaller.
type MockiKeeper struct {
}
MockiKeeper is a mock of iKeeper interface.
NewMockiKeeper creates a new mock instance.
func (m *MockiKeeper) EXPECT() *MockiKeeperMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockiKeeperMockRecorder struct {
}
MockiKeeperMockRecorder is the mock recorder for MockiKeeper.
type MustLoadFunc = func(Loader)
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, like having a "business card" with a specific name that others can use to find them.
The GonerName() method should return a unique string identifier for the component. This name acts as the component's "business card" and 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 - Distinguishing between different instances of the same type
Example usage:
type MyNamedComponent struct {
gone.Flag
}
func (c *MyNamedComponent) GonerName() string {
return "myComponent" // This component's "business card"
}
NamedProvider is an interface for providers that can create dependencies based on name and type. Think of it as a "master craftsman" with a business card who can create any type of component based on specific requirements. 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
This provider acts like a "versatile craftsman" who can adapt their skills to create different types of components based on the specific type requested and configuration provided.
Parameters for Provide:
- tagConf: Configuration string from the struct tag that requested this dependency, like a "detailed work order" specifying requirements
- t: The `reflect.Type` of the dependency being requested, like a "blueprint" showing what type of component to create
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 the type blueprint
return &Config{}, nil
}
NoneParamProvider is a simplified Provider interface for components that provide dependencies without requiring tag configuration. Think of it as a "simple factory" that creates standard products without needing special instructions. 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
This provider acts like a "standard craftsman" who creates the same type of component every time without needing special instructions or customization.
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 interface {
Apply(c *coffin) error
}
Option is an interface for configuring Goners loaded into the gone framework.
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() 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.
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() Option
func MediumStartPriority() 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() 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
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 = Application
Preparer is a type alias for Application, representing the main entry point for application setup and execution.
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 Hook.
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
}
```
Provider is a generic interface for components that can provide dependencies of type T. Think of it as a "smart factory" that can create specific types of components on demand. 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
The Provider acts like a "specialized craftsman" who knows how to create specific types of components based on the requirements (tagConf) provided.
Parameters for Provide:
- tagConf: Configuration string from the struct tag that requested this dependency, like a "work order" specifying what kind of component is needed
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 // Creates a new Config based on requirements
}
type RunOption interface {
Apply(*Application)
}
func OpWaitEnd() RunOption
StructFieldInjector is an interface for components that can inject dependencies into struct fields. Think of it as a "specialized installer" who knows how to install specific components into struct fields based on installation instructions. 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
This injector acts like a "field specialist" who can precisely install components into specific struct fields based on the field's requirements and configuration.
Parameters for Inject:
- tagConf: Configuration string from the struct tag that requested this dependency, like "installation instructions" specifying how to inject
- field: The `reflect.StructField` that requires injection, like the "installation location" specification
- fieldValue: The actual field value to be modified during injection
Returns:
- error: Any error that occurred during injection
StructInjector defines the interface for components that can inject dependencies into struct fields. Think of it as an experienced "assembly worker" who can automatically identify which fields in a struct need "component installation", then find suitable components from the "parts warehouse" and precisely "install" them in the specified locations. It's like assembling a computer where the worker automatically installs corresponding hardware based on the motherboard's interfaces.
The interface requires implementing:
- InjectStruct: Injects dependencies into struct fields based on gone tags
Work Flow:
- Field Scanning: Checks struct fields with specific tags
- Component Matching: Finds corresponding components based on field types and tag information
- Precise Installation: "Installs" found components into corresponding fields
Application Scenarios:
- Component Initialization: Automatically assembles dependencies after component creation
- Test Preparation: Automatically injects mock dependencies for test objects
- Dynamic Assembly: Supplements dependencies for existing objects at runtime
Example usage: ```go
type MyGoner struct {
gone.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 interface {
}
XProvider is a Goner Provider was created by WrapFunctionProvider.
func WrapFunctionProvider[P, T any](fn FunctionProvider[P, T]) *XProvider[T]
WrapFunctionProvider can wrap a FunctionProvider to a Provider.