Documentation
¶
Index ¶
- 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 SetValue(rv reflect.Value, v any, value string) error
- func SortCoffins(coffins []*coffin)
- func TagStringParse(conf string) (map[string]string, []string)
- func Test(fn any)
- type AfterStart
- type AfterStartProvider
- type AfterStop
- type AfterStopProvider
- 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(fn ...any)
- func (s *Application) Serve()
- func (s *Application) Test(fn any)
- func (s *Application) WaitEnd() *Application
- type BError
- type BeforeInitiator
- type BeforeInitiatorNoError
- type BeforeStart
- type BeforeStartProvider
- type BeforeStop
- type BeforeStopProvider
- type BusinessError
- type Component
- type ConfigProvider
- type Configure
- type Core
- func (s *Core) Check() ([]dependency, error)
- func (s *Core) GetGonerByName(name string) any
- func (s *Core) GetGonerByType(t reflect.Type) any
- func (s *Core) GonerName() string
- func (s *Core) InjectFuncParameters(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (args []reflect.Value, err error)
- func (s *Core) InjectStruct(goner any) error
- func (s *Core) InjectWrapFunc(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (func() []any, error)
- func (s *Core) Install() error
- func (s *Core) Load(goner Goner, options ...Option) error
- func (s *Core) Loaded(key LoaderKey) bool
- func (s *Core) Provide(tagConf string, t reflect.Type) (any, error)
- type Daemon
- 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 LoadFunc
- type Loader
- type LoaderKey
- type Logger
- type LoggerLevel
- type NamedGoner
- type NamedProvider
- type NoneParamProvider
- type Option
- type Preparer
- type Process
- type Provider
- type StructFieldInjector
- type StructInjector
- type TestFlag
- type XProvider
Constants ¶
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 ConfigureName = "configure"
const (
DefaultProviderName = "core-provider"
)
const GONE = "GONE"
const LoggerName = "gone-logger"
const Version = "v2.0.5"
Variables ¶
var Default = NewApp()
Functions ¶
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 GetInterfaceType ¶
GetInterfaceType get interface type
func GetTypeName ¶
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 ¶
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 PanicTrace ¶
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 ¶
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 SafeExecute ¶
SafeExecute 执行可能会触发panic的函数并将panic转换为error
func SortCoffins ¶
func SortCoffins(coffins []*coffin)
SortCoffins sorts a slice of coffins by their order
func TagStringParse ¶
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
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 (*Application) AfterStart ¶
func (s *Application) AfterStart(fn Process) *Application
AfterStart registers a function to be called after starting the application. The function will be executed after all daemons have been started. Returns the Application instance for method chaining.
func (*Application) AfterStop ¶
func (s *Application) AfterStop(fn Process) *Application
AfterStop registers a function to be called after stopping the application. The function will be executed after all daemons have been stopped. Returns the Application instance for method chaining.
func (*Application) BeforeStart ¶
func (s *Application) BeforeStart(fn Process) *Application
BeforeStart registers a function to be called before starting the application. The function will be executed before any daemons are started. Returns the Application instance for method chaining.
func (*Application) BeforeStop ¶
func (s *Application) BeforeStop(fn Process) *Application
BeforeStop registers a function to be called before stopping the application. The function will be executed before any daemons are stopped. Returns the Application instance for method chaining.
func (*Application) End ¶
func (s *Application) End() *Application
End triggers application termination by sending a SIGINT signal. Returns the Application instance for method chaining.
func (*Application) Load ¶
func (s *Application) Load(goner Goner, options ...Option) *Application
Load loads a Goner into the Application's loader with optional configuration options. It wraps the Core.Load() method and panics if loading fails.
Parameters:
- goner: The Goner instance to load
- options: Optional configuration options for the Goner
Available Options:
- Name(name string): Set custom name for the Goner
- IsDefault(): Mark this Goner as the default implementation
- OnlyForName(): Only register by name, not as provider
- ForceReplace(): Replace existing Goner with same name/type
- Order(order int): Set initialization order (lower runs first)
- FillWhenInit(): Fill dependencies during initialization
Returns the Application instance for method chaining
func (*Application) Loads ¶
func (s *Application) Loads(loads ...LoadFunc) *Application
Loads executes multiple LoadFuncs in sequence to configure the Application Parameters:
- loads: Variadic LoadFunc parameters that will be executed in order
Each LoadFunc typically loads configurations or components. If any LoadFunc fails during execution, it will trigger a panic.
Returns:
- *Application: Returns the Application instance itself for method chaining
func (*Application) Run ¶
func (s *Application) Run(fn ...any)
Run initializes the application, injects dependencies into the provided function, executes it, and then performs cleanup. The function can have dependencies that will be automatically injected. Panics if dependency injection or execution fails.
Parameters:
- fn: The function to execute with injected dependencies
func (*Application) Serve ¶
func (s *Application) Serve()
Serve initializes the application, starts all daemons, and waits for termination signal. After receiving termination signal, performs cleanup by stopping all daemons.
func (*Application) Test ¶
func (s *Application) Test(fn any)
func (*Application) WaitEnd ¶
func (s *Application) WaitEnd() *Application
WaitEnd blocks until the application receives a termination signal (SIGINT, SIGTERM, or SIGQUIT). Returns the Application instance for method chaining.
type BError ¶
type BError struct {
// contains filtered or unexported fields
}
BError Business error implementation
func (*BError) GetStatusCode ¶
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 ¶
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 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 ¶
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 ¶
Configure defines the interface for configuration providers Get retrieves a configuration value by key, storing it in v, with a default value if not found
type Core ¶
type Core struct {
Flag
// contains filtered or unexported fields
}
func NewCore ¶
func NewCore() *Core
NewCore creates and initializes a new Core instance. It initializes the internal maps for tracking dependencies by name and type, and loads itself as a Goner to enable self-injection. Returns a pointer to the initialized Core.
func (*Core) Check ¶
Check performs dependency validation and determines initialization order: 1. Collects all dependencies between components 2. Validates there are no circular dependencies 3. Determines optimal initialization order based on dependencies 4. Returns ordered list of components to initialize and any validation errors
func (*Core) GetGonerByName ¶
func (*Core) InjectFuncParameters ¶
func (s *Core) InjectFuncParameters(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (args []reflect.Value, err error)
InjectFuncParameters injects parameters into a function by: 1. Using injectBefore hook if provided 2. Using Core's Provide method to get dependencies 3. Creating and filling struct parameters if needed 4. Using injectAfter hook if provided Returns the injected parameter values or error if injection fails
func (*Core) InjectStruct ¶
func (*Core) InjectWrapFunc ¶
func (s *Core) InjectWrapFunc(fn any, injectBefore FuncInjectHook, injectAfter FuncInjectHook) (func() []any, error)
InjectWrapFunc wraps a function with dependency injection. It injects dependencies into the function parameters and returns a wrapper function that: 1. Calls the original function with injected parameters 2. Converts return values to []any, handling nil interface values appropriately Parameters:
- fn: The function to wrap
- injectBefore: Optional hook called before standard injection
- injectAfter: Optional hook called after standard injection
Returns:
- Wrapper function that returns results as []any
- Error if injection fails
func (*Core) Load ¶
Load loads a Goner into the Core with optional configuration options.
A Goner can be registered by name if it implements NamedGoner interface. If a Goner with the same name already exists: - If forceReplace option is true, the old one will be replaced - Otherwise returns LoadedError
If the Goner implements Provider interface (has Provide method), it will be registered as a provider. If a provider for the same type already exists: - If forceReplace option is true, the old one will be replaced - Otherwise returns LoadedError
Parameters:
- goner: The Goner instance to load
- options: Optional configuration options for the Goner
Available Options:
- Name(name string): Set custom name for the Goner
- IsDefault(): Mark this Goner as the default implementation
- OnlyForName(): Only register by name, not as provider
- ForceReplace(): Replace existing Goner with same name/type
- Order(order int): Set initialization order (lower runs first)
- FillWhenInit(): Fill dependencies during initialization
Returns error if:
- Any option.Apply() fails
- A Goner with same name already exists (without forceReplace)
- A Provider for same type already exists (without forceReplace)
type Daemon ¶
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 ¶
Error normal error
func NewError ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
FunctionProvider is an experimental type that may change or be removed in future releases.
type Goner ¶
type Goner interface {
// contains filtered or unexported methods
}
Goner is the base interface that all components managed by Gone must implement. It acts as a marker interface to identify types that can be loaded into the Gone container.
Any struct that embeds the Flag struct automatically implements this interface. This allows Gone to verify that components are properly configured for dependency injection.
Example usage:
type MyComponent struct {
gone.Flag // Embeds Flag to implement Goner
}
type GonerKeeper ¶
type GonerKeeper interface {
// GetGonerByName retrieves a component by its name.
// The name should match either the component's explicit name set via gone.Name() option
// or the name returned by its GonerName() method if it implements NamedGoner.
//
// Parameters:
// - name: The name of the component to retrieve
//
// Returns:
// - any: The component instance if found, nil otherwise
GetGonerByName(name string) any
// GetGonerByType retrieves a component by its type.
// The type should match either the exact type of the component or
// an interface type that the component implements.
//
// Parameters:
// - t: The reflect.Type of the component to retrieve
//
// Returns:
// - any: The component instance if found, nil otherwise
GetGonerByType(t reflect.Type) any
}
GonerKeeper interface defines methods for retrieving components from the Gone container. It provides dynamic access to components at runtime, allowing components to be looked up by either name or type.
The interface requires implementing:
- GetGonerByName: Retrieves a component by its registered name
- GetGonerByType: Retrieves a component by its type
Example usage: ```go
type MyComponent struct {
gone.Flag
keeper gone.GonerKeeper `gone:"*"`
}
func (m *MyComponent) Init() error {
// Get component by name
if svc := m.keeper.GetGonerByName("service"); svc != nil {
// Use the service
}
// Get component by type
if logger := m.keeper.GetGonerByType(reflect.TypeOf(&Logger{})); logger != nil {
// Use the logger
}
return nil
}
```
type Initiator ¶
type Initiator interface {
Init() error
}
Initiator interface defines components that need initialization after dependencies are injected. Components implementing this interface will have their Init() method called during Gone's initialization phase. Init() is called after all dependencies are filled and BeforeInit() hooks (if any) have completed.
The Init() method should: - Perform any required setup or validation - Initialize internal state - Establish connections to external services - Return an error if initialization fails
Example usage:
type MyComponent struct {
gone.Flag
db *Database `gone:"*"`
}
func (c *MyComponent) Init() error {
return c.db.Connect()
}
type InitiatorNoError ¶
type InitiatorNoError interface {
Init()
}
InitiatorNoError interface defines components that need initialization but don't return errors. Similar to Initiator interface, but Init() does not return an error. Components implementing this interface will have their Init() method called during Gone's initialization phase, after dependencies are filled and BeforeInit() hooks (if any) have completed.
The Init() method should: - Perform any required setup or validation - Initialize internal state - Establish connections to external services - Handle errors internally rather than returning them
Example usage:
type MyComponent struct {
gone.Flag
logger *Logger `gone:"*"`
}
func (c *MyComponent) Init() {
c.logger.Info("Initializing MyComponent")
// perform initialization...
}
type InnerError ¶
InnerError which has stack, and which is used for Internal error
type LoadFunc ¶
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
}
```
type Loader ¶
type Loader interface {
// Load adds a component to the Gone container with optional configuration.
//
// Parameters:
// - goner: The component to load. Must implement Goner interface.
// - options: Optional configuration for how the component should be loaded.
//
// Returns:
// - error: Any error that occurred during loading
Load(goner Goner, options ...Option) error
// Loaded checks if a component identified by the given LoaderKey has been loaded.
//
// Parameters:
// - LoaderKey: The unique identifier for the component to check.
//
// Returns:
// - bool: true if the component is loaded, false otherwise
Loaded(LoaderKey) bool
}
Loader defines the interface for loading components into the Gone container. It provides methods to load new components and check if components are already loaded.
The interface requires implementing:
- Load: Loads a component into the container with optional configuration
- Loaded: Checks if a component is already loaded
type LoaderKey ¶
type LoaderKey struct {
// contains filtered or unexported fields
}
LoaderKey is a unique identifier for tracking loaded components in the Gone container. It uses an internal counter to ensure each loaded component gets a unique key.
The LoaderKey is used to: - Track which components have been loaded - Prevent duplicate loading of components - Provide a way to check component load status
func GenLoaderKey ¶
func GenLoaderKey() LoaderKey
GenLoaderKey will return a brand new, never-before-used LoaderKey
type Logger ¶
type Logger interface {
Infof(msg string, args ...any)
Errorf(msg string, args ...any)
Warnf(msg string, args ...any)
Debugf(msg string, args ...any)
GetLevel() LoggerLevel
SetLevel(level LoggerLevel)
}
func GetDefaultLogger ¶
func GetDefaultLogger() Logger
type LoggerLevel ¶
type LoggerLevel int8
const ( DebugLevel LoggerLevel = -1 InfoLevel LoggerLevel = 0 WarnLevel LoggerLevel = 1 ErrorLevel LoggerLevel = 2 )
type NamedGoner ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 XProvider ¶
XProvider is an experimental type that may change or be removed in future releases.
func WrapFunctionProvider ¶
func WrapFunctionProvider[P, T any](fn FunctionProvider[P, T]) *XProvider[T]
WrapFunctionProvider is an experimental function that may change or be removed in future releases.