go-scopes/common/common.go

92 lines
1.6 KiB
Go

package common
type Config interface {
Name() string
Starter() StartFct
Children() []Config
Add(Config)
}
type Services map[string]Context
type ContextState interface{}
type Context interface {
Config() Config
Parent() Context
Services() Services
ChildContext(Config) Context
State() ContextState
WithState(ContextState) Context
}
type StartFct = func(Context)
// Context implementation
type context struct {
cfg Config
parent Context
children []Context
state ContextState
}
func (ctx *context) Config() Config {
return ctx.cfg
}
func (ctx *context) Parent() Context {
return ctx.parent
}
func (ctx *context) Services() Services {
return ctx.parent.Services()
}
func (ctx *context) ChildContext(cfg Config) Context {
cctx := makeCtx(cfg, ctx)
ctx.Services()[cfg.Name()] = cctx
ctx.children = append(ctx.children, cctx)
return cctx
}
func (ctx *context) State() ContextState {
return ctx.state
}
func (ctx *context) WithState(state ContextState) Context {
ctx.state = state
return ctx
}
func makeCtx(cfg Config, parent Context) *context {
return &context{
cfg: cfg,
parent: parent,
}
}
// top-level application context
type appContext struct {
*context
services Services
}
func (ctx *appContext) ChildContext(cfg Config) Context {
cctx := makeCtx(cfg, ctx)
ctx.services[cfg.Name()] = cctx
ctx.children = append(ctx.children, cctx)
return cctx
}
func (ctx *appContext) Services() Services {
return ctx.services
}
func AppContext(cfg Config) Context {
return &appContext{
context: makeCtx(cfg, nil),
services: Services{},
}
}