nurse/check/registry.go

58 lines
1,013 B
Go
Raw Permalink Normal View History

2022-05-13 13:38:19 +00:00
package check
import (
"errors"
"fmt"
"strings"
"sync"
)
var (
ErrModuleNameConflict = errors.New("module name conflict")
ErrNoSuchModule = errors.New("no module of given name known")
)
func NewRegistry() *Registry {
return &Registry{
mods: make(map[string]*Module),
}
}
type (
Registry struct {
lock sync.RWMutex
mods map[string]*Module
}
)
func (r *Registry) Register(modules ...*Module) error {
2022-05-13 13:38:19 +00:00
r.lock.Lock()
defer r.lock.Unlock()
for _, mod := range modules {
modName := strings.ToLower(mod.Name())
2022-05-13 13:38:19 +00:00
if _, ok := r.mods[modName]; ok {
return fmt.Errorf("%w: %s", ErrModuleNameConflict, modName)
}
r.mods[modName] = mod
2022-05-13 13:38:19 +00:00
}
return nil
}
2022-06-09 20:40:32 +00:00
//nolint:ireturn // required to implement interface
2022-05-13 13:38:19 +00:00
func (r *Registry) Lookup(modName string) (CheckerLookup, error) {
r.lock.RLock()
defer r.lock.RUnlock()
modName = strings.ToLower(modName)
if mod, ok := r.mods[modName]; !ok {
return nil, fmt.Errorf("%w: %s", ErrNoSuchModule, modName)
} else {
return mod, nil
}
}