ServiceLifeCycle
type ServiceLifeCycle struct {
Deps Dependencies
ExtraDeps []CustomService
AsyncMode map[common.ServiceStatus]bool
AfterInit func(ctx context.Context, deps Dependencies) error
OnInterrupt func(ctx conntext.Context, reasons []int)
}Deps Dependencies: List of services that the service is depended on
Example:
api.go
func (a *API) Init(ctx context.Context) (*gobs.ServiceLifeCycle, error) {
return &gobs.ServiceLifeCycle{
Deps: []interface{
&log.Log{},
&conf.Config{},
}
}, nil
}ExtraDeps []CustomService: List of services inform of extra information. It is used to make the service depend on the other services which are not the same with the ones existed in the gobs.
Example: API requires 2 independent instances of Log and Config without reuse the instances which are commonly shared in the gobs
api.go
import gCommon "github.com/xarest/gobs/common"
func (a *API) Init(ctx context.Context) (*gobs.ServiceLifeCycle, error) {
return &gobs.ServiceLifeCycle{
ExtraDeps: []gobs.CustomService{
{
Name: "Log-2",
Instance: &log.Log{}
},
{
Name: "Cfg-2",
Instance: &cfg,
Status: gCommon.StatusSetup,
},
}
}, nil
}AsyncMode: Define stages of a service work in async mode. It is useful to not pending other services when this service is waiting for another processes.
Example: API has Start method which should run in async mode. This configuration will help other instannces who does not depend on API can run without waiting for API to finish the Start stage.
api.go
import gCommon "github.com/xarest/gobs/common"
func (a *API) Init(ctx context.Context) (*gobs.ServiceLifeCycle, error) {
return &gobs.ServiceLifeCycle{
AsyncMode: map[gCommon.ServiceStatus]bool{
gCommon.StatusStart: true,
},
}, nil
}AfterInit: Callback afterInitof service run successfully, when all of its dependencies are ready to be injected. Usually used for filling internal fields of Service struct
Example: API depends on log & config instances. When both of them finish init step, AfterInit of API is called to load those instances into API instance.
api.go
func (a *API) Init(ctx context.Context) (*gobs.ServiceLifeCycle, error) {
return &gobs.ServiceLifeCycle{
Deps: []interface{
&log.Log{},
&conf.Config{},
},
AfterInit: func(ctx context.Context, deps Dependencies) error {
a.log = deps[0]
a.cfg = deps[1]
}
}, nil
}OnInterrupt: Callback when gobs is interrupted atstartstate and it is going to be stopped. This callback is critical thus logic inside must be execute as quick as possible. Don’t try any blocking execution inside this method
Example: Log will show warning when a signal interrupt gobs
log.go
func (l *Log) Init(ctx context.Context) (*gobs.ServiceLifeCycle, error) {
return &gobs.ServiceLifeCycle{
OnInterrupt: func(ctx context.Context, reasons []int) {
l.Warn("The appication has been interrupted")
}
}, nil
}