services map as own type; function makeCtx; record context children

This commit is contained in:
Helmut Merz 2023-06-03 08:41:55 +02:00
parent 87ff5d5d93
commit 9797c3515a

View file

@ -7,10 +7,12 @@ type Config interface {
Add(Config) Add(Config)
} }
type Services map[string]Context
type Context interface { type Context interface {
Config() Config Config() Config
Parent() Context Parent() Context
Services() map[string]Context Services() Services
ChildContext(Config) Context ChildContext(Config) Context
} }
@ -21,6 +23,7 @@ type StartFct = func(Context)
type context struct { type context struct {
cfg Config cfg Config
parent Context parent Context
children []Context
} }
func (ctx *context) Config() Config { func (ctx *context) Config() Config {
@ -31,36 +34,43 @@ func (ctx *context) Parent() Context {
return ctx.parent return ctx.parent
} }
func (ctx *context) Services() map[string]Context { func (ctx *context) Services() Services {
return ctx.parent.Services() return ctx.parent.Services()
} }
func (ctx *context) ChildContext(cfg Config) Context { func (ctx *context) ChildContext(cfg Config) Context {
cctx := context{cfg, ctx} cctx := makeCtx(cfg, ctx)
ctx.Services()[cfg.Name()] = &cctx ctx.Services()[cfg.Name()] = cctx
return &cctx ctx.children = append(ctx.children, cctx)
return cctx
}
func makeCtx(cfg Config, parent Context) *context {
ctx := context{cfg, parent, nil}
return &ctx
} }
// top-level application context // top-level application context
type appContext struct { type appContext struct {
*context *context
services map[string]Context services Services
} }
func (ctx *appContext) ChildContext(cfg Config) Context { func (ctx *appContext) ChildContext(cfg Config) Context {
cctx := context{cfg, ctx} cctx := makeCtx(cfg, ctx)
ctx.services[cfg.Name()] = &cctx ctx.services[cfg.Name()] = cctx
return &cctx ctx.children = append(ctx.children, cctx)
return cctx
} }
func (ctx *appContext) Services() map[string]Context { func (ctx *appContext) Services() Services {
return ctx.services return ctx.services
} }
func AppContext(cfg Config) Context { func AppContext(cfg Config) Context {
return &appContext{ return &appContext{
context: &context{cfg, nil}, context: makeCtx(cfg, nil),
services: map[string]Context{}, services: Services{},
} }
} }